views:

16

answers:

1

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?

A: 

I'm going to throw this out there...

RedirectToAction has a return type of RedirectToRouteResult. This is called by several of the action methods in the above pseudo code.

According to this possibly outdated blog entry...

4.RedirectResult and RedirectToRouteResult always calls TempData.Keep()

and

Calling Keep() from within an action method ensures that none of the items in TempData are removed at the end of the current request, even if they were read. The second overload can be used to retain specific items in TempData.

So it looks like my TempData values are being automatically flagged. I verified this by seeing these values show up under _initialKeys within TempData.

Mayo