2014-03-24 47 views
0

對於HttpContext.Items有限制嗎?如果是的話,替代方案是什麼?單擊鏈接後MVC HttpContext.Current.Items爲空

FirstController索引視圖我正在設置一個項目。

public class FirstController : Controller 
{ 
    public ActionResult Index() 
    { 
     HttpContext.Items["Sample"] = "DATA"; 
     return View(); 
    } 
} 

<a href="/SecondController/TestView">Sample Link</a> 

當我試圖讓在值SecondController它給我空的,而不是「DATA」

public class SecondController : Controller 
{ 
    public ActionResult TestView() 
    { 
     string text = HttpContext.Current.Items["Sample"]; 
     return View(); 
    } 
} 

回答

0

Items歡迎使用屬性的HttpContext的使用在一個請求共享數據。當您將值設置爲第一個控制器中的Sample鍵時,只要請求管道完成,它就會被丟棄。

我認爲你正在尋找HttpSessionState,通過HttpContext.Session屬性可以訪問。您可以在代碼中將HttpContext.Items替換爲HttpContext.Session,它應該按原樣運行。

public class FirstController : Controller 
{ 
    public ActionResult Index() 
    { 
     HttpContext.Session["Sample"] = "DATA"; 
     return View(); 
    } 
} 

public class SecondController : Controller 
{ 
    public ActionResult TestView() 
    { 
     string text = HttpContext.Current.Session["Sample"]; 
     return View(); 
    } 
} 
0

HttpContext的數據保存在單個HTTP請求的內存中,然後它們被丟棄。

1
HttpContext.Items

「獲取一個鍵/值集合可用於HTTP請求期間組織和共享數據[...]

你需要像一個會話狀態機制的請求之間保存數據:

Session["Sample"] = "DATA"; 

what is correct way of storing data between requests in asp.mvc 見。

+0

我不想使用會話。這可以使用自定義屬性來完成嗎? – CoolArchTek

+0

自定義屬性不會解決您的問題。解釋爲什麼你不想使用會話,請點擊「[在asp.mvc中請求之間存儲數據的正確方式](http://stackoverflow.com/questions/15336991/what-is-correct-way -of-storage-data-between-requests-in-asp-mvc)「鏈接來查看備選方案。 – CodeCaster