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

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

Leave a Comment