I have the following class in a Controller passing data to a View:
public ActionResult ControllerToView(){
...
TempData["example"] = "this is a message!";
...
return Redirect("http://myViewPageLink");
}
In my View, I am trying to access the TempData dictionary with:
@if(myCondition){
var test = TempData["example"];
<p>@test</p>
}
"myCondition" is always satisfied, but the TempData dictionary is always empty. Any ideas why? Is there any aditional code I have to write in order to make TempData available in the view?
It might be useful information that before calling my controller method I have an ajax request to another method in the same controller.
You should know that TempDataDictionary
used for short-term instance. Its value available during current & subsequent request when the next request surely redirects to next view (suitable for one-time messages). Any value you've assigned to TempDataDictionary
will be discarded after completion of subsequent request, as "normal read".
So that your current request consists of this sequence:
TempDataDictionary
TempDataDictionary
content may discarded here if no Keep
or Peek
method used to persist dataTempDataDictionary
is empty)Hence the correct way to use TempDataDictionary
is passing value directly to view in current request or using redirect to another controller action method as subsequent request, as this example:
Controller
public ActionResult ControllerToView()
{
...
TempData["example"] = "this is a message!";
...
// returning view counts as providing response
return View();
}
View
@if (myCondition)
{
var test = TempData["example"]; // showing message
<p>@test</p>
}
The request sequence for above example is given below:
TempDataDictionary
TempDataDictionary
is not empty)If you use RedirectResult
then trying to read/display value in TempData
without specifying the 'next action', it considered as "normal read" & not persisted for next request. The 'next action' you can use: Keep
or Peek
(either in view or controller action):
// Keep
var test = TempData["example"];
TempData.Keep("example");
// Peek
var test = TempData.Peek("example");
NB: If you want setting values to be persist across multiple requests, I strongly prefer HttpSessionState
:
// set session state
Session["example"] = "[any value]";
// read in another request
var testing = Session["example"];
References: