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:
- Use submits form.
- Code (special action filter) adds model to TempData , redirects to logon page.
- 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:
- Items are only removed from TempData at the end of a request if they have been tagged for removal.
- Items are only tagged for removal when they are read.
- Items may be untagged by calling TempData.Keep(key).
- 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?
StatefulAuthorize
won't be called. – ScapeStatefulAuthorize
is called in the initial POST, e.g when the user is unauthenticated and tries to submit the form. I don't want (nor expect it) to get called when i invoke the method manually. Anyway, Darin has summed up my problem. Bottom line - i dont think i should be using TempData, i should be using Session. – Condensate