简体   繁体   中英

Which is better, Session or 2 TempData in ASP.NET MVC?

I found that I shouldn't use Session a lot in ASP MVC here , here and in other places.

So, I want to know if it's better to use TempData like I did below or not.

public ActionResult Action1()
{
  if (SomeCondition)
  {
     /*
       I want to show alert to user based on this value that should appear in Action2 view
       So, is it better to:
       1. Session["user"] = "something";
       2. TempData["user"] = "something";
     */
     return RedirectToAction("Action2");
  }
     return View();
}

public ActionResult Action2()
{
   /*
      1. I can read Session["user"] in the view
      2. TempData["user"] = TempData["user"].ToString();
         Now I can read TempData in the view
   */
   return View();
}

TempData is a provider that uses Session by default. It can be changed to be a cookie-based provider, though.

The only real difference is that TempData stores the data only until it is read again, where Session will store the data until a timeout expires.

There is no perfect solution for storing data between requests. When possible, you should avoid it. In MVC you can do this fairly easily by loading the data into the View and posting the ViewModel back to the controller where you can read the data again.

Also, see Think twice about using session state for some possible alternatives to session state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM