6

I have a controller action something similar to the below, TempData was initialized by my framework. I've noticed that TempData doesn't clear out the value once it is read as shown in the action "EmployeeUnderAge".

When does TempData clears the data that has been read?

public class HomeController : Controller
{
    public ActionResult Index(int iD)
    {
        var employeeAge = (int)TempData["Age"];
        RouteData.Values.Add("Age", employeeAge);
        return RedirectToAction("EmployeeUnderAge");
    }

    public ActionResult EmployeeUnderAge(int employeeAge)
    {
        var stillInTempData = (employeeAge == ((int) TempData["Age"]));
        return (stillInTempData) ? View("Index") : View("Error");
    }
}
Viktor Bahtev
  • 4,858
  • 2
  • 31
  • 40
Kiran Vedula
  • 553
  • 6
  • 14

1 Answers1

9

Below are some of the key points to note when using Temp data.

  1. A read access to temp data doesn't remove items from the dictionary immediately, but only marks for deletion.

  2. TempData will not always remove the item that has been read. It only removes the item when an action results in an HTTP 200 (OK) status code (ie: ViewResult/JsonResult/ContentResult etc)

  3. In case of actions that result in an HTTP 302 (such as any redirect actions), the data is retained in storage even when it is accessed which is the case in my question. TempData apparently is designed for passing data to different controllers/actions and hence doesn't clearing out during redirects is justified

JNYRanger
  • 6,829
  • 12
  • 53
  • 81
Kiran Vedula
  • 553
  • 6
  • 14
  • Beat me to it! I would add on to this that the removal from TempData usually occurs later on in the ASP.NET pipeline after the method within the controller returns so checking if the value is still there within the same method can have unpredictable results. TempData is usually only used for passing data between controller actions when redirects are used. – JNYRanger Sep 14 '15 at 18:40
  • Absolutely true.As the backing store is ASP.Net session state, one can access it until it is cleared by ASP.Net pipeline – Kiran Vedula Sep 14 '15 at 18:55