In ASP.NET MVC 2, TempData
values persist until the session ends or until they are read. In the words of Microsoft...
The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.
I thought I understood this but I just came across unusual behavior in my application where a TempData
value was available and it should not have been available. In general, I have a controller with a series of actions where the first action sets a TempData
value, the next few actions read and then set that TempData
value, and the final action reads the TempData value. Pseudo code below...
[HttpPost]
public ActionResult Step1()
{
TempData["bar"] = foo;
return RedirectToAction("Step2");
}
public ActionResult Step2()
{
var foo = TempData["bar"];
TempData["bar"] = foo;
return View();
}
[HttpPost]
public ActionResult Step2()
{
var foo = TempData["bar"];
TempData["bar"] = foo;
return RedirectToAction("Step3");
}
public ActionResult Step3()
{
var foo = TempData["bar"];
TempData["bar"] = foo;
return View();
}
[HttpPost]
public ActionResult Step3()
{
var foo = TempData["bar"];
return RedirectToAction("AnotherAction", "AnotherController");
}
My belief was that after reading a value, it would no longer be available in TempData. But I started stepping through the code and while the key/value would be added to TempData on assignment, it would never go away when I pulled the value from TempData (even when I arrived in a different controller).
The only way I am able to get it to go away is to manually hit an action that reads from TempData
.
Can anyone provide any pointers to help me better understand what is going on with TempData
persistence in ASP.NET MVC 2?