queen3
queen3

Reputation: 15501

ASP.NET MVC TempData used for wrong request

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.

Upvotes: 1

Views: 638

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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).

Upvotes: 2

Related Questions