views:

141

answers:

1

I use TempData to keep ModelState during redirects (using MvcContrib technique). This works fine. However, in rare cases, user aborts request and then immediate fires another (e.g. quickly clicks on another menu item). This causes ModelState errors to appear on that page, for which it does not belong.

The problem is that TempData is stored in Session. This means, ANY request can grab it, e.g. the one that comes first to the server.

Are there any known workarounds? E.g. keep "destination page" in the TempData along with saved ModelState.

+1  A: 

In my opinion TempData should only be used in actions that redirect immediately. For example:

public ActionResult Index()
{
    TempData["foo"] = "bar";
    return RedirectToAction("About");
}

public ActionResult About() 
{
    var foo = TempData["foo"];
    return View();
}

You should avoid storing something into the TempData and render a view:

public ActionResult Index()
{
    TempData["foo"] = "bar";
    // bad :-(
    return View("About");
}

Use Session to achieve what you are looking for or add some unique ID that allow you to identify the correct request.

Another common technique you could use instead of TempData is to serialize the model on the client (a sort of a ViewState if you will).

Darin Dimitrov
My question is exactly about "actions that redirect immediately". Issue would not happen if I just render view after assigning tempdata. And TempDate _DO_ use Session so this advice makes no sense. The very problem is that there's no such thing as "immediate redirect" - another request caused by user click can abort it and come next. As for serializing ModelState in the view, I thought about it, but thanks for the link.
queen3
No, I can't serialize in view. The flow is "get POST - check errors - set ModelState - redirect to page that shows messages". There's no "view" between "check errors" and "page that shows messages".
queen3