Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Session and ViewData in Asp.net-MVC?

When should I use one versus the other? I want to cache a certain object on startup and reuse around the application. Which sounds like the better solution (ViewData or Session)?

like image 218
leora Avatar asked Nov 07 '10 02:11

leora


People also ask

Which is faster ViewData or ViewBag?

ViewBag will be slower than ViewData; but probably not enough to warrant concern.

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 ViewData?

All three objects are available as properties of both the view and controller. As a rule of thumb, you'll use the ViewData, ViewBag, and TempData objects for the purposes of transporting small amounts of data from and to specific locations (e.g., controller to view or between views).


1 Answers

ViewData is a per-request object used to send information from the controller to the view.
Each action invocation gets its own ViewData; the ViewData doesn't last beyond the view.

Session State is a per-user storage container which allows you to store data for a specific user session (identified by a cookie)

If you want to share a global object, you should probably make it a singleton (in a static property) or put it in Application state.
Make sure that it's thread-safe. (Or use a [ThreadStatic] field carefully)

like image 173
SLaks Avatar answered Oct 20 '22 23:10

SLaks