Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right time for ViewData, ViewBag, Session, TempData

I was editing a project and I saw a Session[""] in one controller method and TempData[""] in another. Is there a difference between the 4 or is it just 4 ways to do the same thing.

like image 682
MrM Avatar asked Oct 01 '12 16:10

MrM


People also ask

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.

Which is faster ViewBag or ViewData?

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

When should we use ViewData in MVC?

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

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.


2 Answers

  • ViewData/ViewBag - valid only for the duration of the current request.
    You set it in a controller action and use it in the view, then it disappears.
    The difference is that the first is a dictionary whereas the second is just a dynamic wrapper around this dictionary.
    Both point to the same data though.
    ViewBag was introduced in ASP.NET MVC 3.

Example:

public ActionResult Index() {     ViewData["foo"] = "bar";     return View(); } 

and inside the view you could use this value:

<div>@ViewData["foo"]</div> 

Same with ViewBag but it is dynamic:

public ActionResult Index() {     ViewBag.foo = "bar";     return View(); } 

and inside the view you could use this value:

<div>@ViewBag.foo</div> 

So as you can see ViewData/ViewBag are just an alternative way to pass information to a view from a controller action compared to the classic and recommended way which is using a view model:

public class MyViewModel {     public string Foo { get; set; } } 

and then:

public ActionResult Index() {     var model = new MyViewModel { Foo = "bar" };     return View(model); } 

and inside your strongly typed view:

@model MyViewModel <div>@Html.DisplayFor(x => x.Foo)</div> 

As you can see using view models provide a strongly typed approach in passing information to a view from a controller action.

  • TempData - it allows for persisting information for the duration of a single subsequent request. You store something inside TempData and then redirect. In the target controller action to which you redirected you could retrieve the value that was stored inside TempData.

Example:

public ActionResult Foo() {     TempData["foo"] = "bar";     return RedirectToAction("bar"); }  public ActionResult Bar() {     var value = TempData["foo"] as string;     // use the value here. If you need to pass it to the view you could     // use ViewData/ViewBag (I can't believe I said that but I will leave it for the moment)     return View(); } 

ASP.NET MVC will automatically expire the value that was stored in TempData once you read it. Under the covers ASP.NET MVC persists the information into the Session.

  • Session - same as TempData except that it never expires - it will be valid for all requests, not a single redirect.
like image 178
Darin Dimitrov Avatar answered Sep 21 '22 03:09

Darin Dimitrov


ASP.net MVC introduced ViewData, ViewBag, TempData, Session to pass data between controller to view.

ViewData

ViewData is implemented by using ViewDataDictionary class which stored in CurrentRequestContext. So, ViewData life-cycle will end when the current request ends.

ViewBag is also like ViewData, and only difference is it enable dynamically sharing the data using dynamics objects.

TempData is a very short-lived instance, and you should only use it during the current and the subsequent requests only.This will be handy if you want to use Redirections(RedirectToAction, RedirectToRoute, Redirect) in ASP.net MVC and pass some data among redirects. TempData stores data in Session but framework disposes the data when current and subsequent requests ends.

Session is long-lived(Never expires) data that belongs to user session.You need to be mindful when you use session variables which can be easily cause issues.

protected void Session_Start(Object sender, EventArgs e) 
{
   int userType = 1;
   HttpContext.Current.Session.Add("_SessionUserType",userType );
}
like image 39
marvelTracker Avatar answered Sep 22 '22 03:09

marvelTracker