TempData Not Being Cleared

RPM1984 picture RPM1984 · Oct 3, 2011 · Viewed 14.5k times · Source

I'm working on an ASP.NET MVC 3 web application, where i use TempData to store a model object, in the scenario where the user is not logged in.

Here's the flow:

  1. Use submits form.
  2. Code (special action filter) adds model to TempData , redirects to logon page.
  3. User redirected back to GET action, which reads TempData and calls POST action directly

After step 3, i would have thought TempData would be cleared?

Here's the code:

[HttpGet]
public ActionResult Foo()
{
    var prefilled = TempData["xxxx"] as MyModel;
    if (prefilled != null)
    {
       return Foo(prefilled);
    }
}

[HttpPost]
[StatefulAuthorize] // handles the tempdata storage and redirect to logon page
public ActionResult Foo(MyModel model)
{
   // saves to db.. etc
}

I found this article which states:

  1. Items are only removed from TempData at the end of a request if they have been tagged for removal.
  2. Items are only tagged for removal when they are read.
  3. Items may be untagged by calling TempData.Keep(key).
  4. RedirectResult and RedirectToRouteResult always calls TempData.Keep().

Well by reading it with TempData["xxx"] isn't that a "read" and therefore they should be tagged for removal?

And the last one concerns me a bit - since i'm doing a Redirect after the POST (P-R-G). But this can't be avoided.

Is there a way i can say "ditch this item". TempData.Remove ? Or am i doing this wrong?

Answer

RPM1984 picture RPM1984 · Oct 3, 2011

Fixed by adding TempData.Remove right after i read it.

Not really happy about this. I thought the whole point of TempData was that i didn't have to do this.

May as well be using Session directly.