0

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();
}
Community
  • 1
  • 1
Ahmed
  • 511
  • 3
  • 6
  • 26
  • It _depends_ on _what_ you are / have to, persist. You can even do so _client-side_ (again, depending on _what you need to persist_). – EdSF Aug 09 '15 at 17:58
  • I meant with the question if one of them is better regarding performance in such scenario, but I've learned from the answer that `TempData` is basically a `Session`. So I think there is no difference, or may be -guessing- even using 2 `TempData` would be worse than a `Session`, because the server would create one, then terminate it, then create another one, then terminate it, instead of creating a `Session` then after timed out, it expires. – Ahmed Aug 09 '15 at 22:26
  • Again, it _depends on what kind of data you need to persist_ .... – EdSF Aug 09 '15 at 23:27

1 Answers1

1

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.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212