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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.