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:
- Request => ActionResult (ControllerToView)
- Set
TempDataDictionary
- Response => RedirectResult
- Request => ViewResult ==> the
TempDataDictionary
content may discarded here if no Keep
or Peek
method used to persist data
- Response => View (with
TempDataDictionary
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:
- Request => ActionResult (ControllerToView)
- Set
TempDataDictionary
- Response => View (
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:
Using Tempdata in ASP.NET MVC - Best practice
When to use ViewBag, ViewData, or TempData
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…