开发者

ASP.NET MVC TempData used for wrong request

开发者 https://www.devze.com 2022-12-24 20:04 出处:网络
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 a

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 m开发者_JAVA百科eans, 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消