Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use TempData vs Session in ASP.Net MVC

I am trying to get the hang of MVC framework so bear with me.

Right now, the only thing I'm using the session store for is storing the current logged in user. My website is simple. For this example, consider three domain objects, Person, Meeting, and File. Users can log in and view a "members only" profile of a meeting and can add files to it, or view a meeting's public "profile" if they aren't logged in.

So, from the meeting's private profile, with a logged in user, I have a "add files" link. This link routes to FileContoller.Add(int meetingId). From this action, I get the meeting the user want to add files to using the meeting id, but after the form is posted, I still need to know which meeting the user is adding files to. That's where my question lies, should I pass the "currently interacting with" meeting through TempData, or add it to the Session store?

This is how I currently have the Add action setup, but it's not working:

    public ActionResult Add(int meetingId)     {         try         {             var meeting = _meetingsRepository.GetById(meetingId);             ViewData.Model = meeting;             TempData[TempDataKeys.CurrentMeeting] = meeting; /* add to tempdata here */         }         catch (Exception)         {             TempData[TempDataKeys.ErrorMessage] = "Unable to add files to this meeting.";             return RedirectToRoute("MeetingsIndex");         }          return View();     }      [AcceptVerbs(HttpVerbs.Post)]     public ActionResult Add(FormCollection form)     {         var member = Session[SessionStateKeys.Member] as Member;         var meeting = TempData[TempDataKeys.CurrentMeeting] as Meeting; /* meeting ends up null here */          if (member == null)         {             TempData[TempDataKeys.ErrorMessage] = "You must be logged in to add files to an meeting.";             return RedirectToRoute("LoginPage");         }          if (meeting == null)          {             TempData[TempDataKeys.ErrorMessage] = "An error occurred. No meeting selected.";             return RedirectToRoute("MeetingsIndex");         }              // add files to meeting          TempData[TempDataKeys.Notification] = "Successfully added.";         return RedirectToRoute("AddFiles", new {meetingId = meeting.MeetingId}); } 

Edit:

Based on most of the answers, can any one provide any examples on what kind of data (other than messages) should be stored in TempData vs Session?

like image 814
scottm Avatar asked Sep 30 '09 20:09

scottm


People also ask

Which is better TempData or session in MVC?

TempData is ideal for short-lived things like displaying validation errors or other messages that we don't need to persist for longer than a single request. Session is ideal choice when we need to persist data for extended periods of time i.e. it is used to store data which is required throughout user session.

When should we use TempData in MVC?

What is TempData and How to Use in MVC? TempData is used to transfer data from the view to the controller, the controller to the view, or from an action method to another action method of the same or a different controller. TempData temporarily saves data and deletes it automatically after a value is recovered.

When should I use ViewBag ViewData or TempData?

To summarize, ViewBag and ViewData are used to pass the data from Controller action to View and TempData is used to pass the data from action to another action or one Controller to another Controller.

Is TempData stored in session?

It is stored in session storage, but there is one crucial difference between TempData and Session : TempData is available only for a user's session, so it persists only till we have read it and gets cleared at the end of an HTTP Request.


1 Answers

TempData is session, so they're not entirely different. However, the distinction is easy to understand, because TempData is for redirects, and redirects only. So when you set some message in TempData and then redirect, you are using TempData correctly.

However, using Session for any kind of security is extremely dangerous. Session and Membership are entirely separate in ASP.NET. You can "steal" sessions from other users, and yes, people do attack web sites this way. So if you want to selectively stop a post information based on whether a user is logged in, look at IsAuthenticated, and if you want to selectively show information based on what type of user is logged in, you use a Role provider. Because GETs can be cached, the only way to selectively allow access to an action in a GET is with AuthorizeAttribute.

Update In response to your edited question: You already have a good example of using TempData in your question, namely, returning a simple error message after a failed POST. In terms of what should be stored in Session (beyond "not much"), I just think of Session as a user-specific cache. Like the non-user-specific Cache, you should not put security-sensitive information there. But it's a good place to stick stuff which is relatively expensive to look up. For example, our Site.Master has the user's full name displayed on it. That is stored in a database, and we don't want to do a database query for it for every page we serve. (An installation of our application is used in a single company, so a user's full name is not considered "security-sensitive.") So if you think of Session as a cache which varies by a cookie which the user has, you won't be far wrong.

like image 76
Craig Stuntz Avatar answered Sep 22 '22 05:09

Craig Stuntz