ViewModel vs ViewData vs ViewBag vs TempData vs Session in MVC

During training sessions, I was often asked by my programmers about passing data from controller to view in ASP.NET MVC. The predominant question is When to use ViewModel, ViewData, ViewBag, TempData or Session? and What are the differences between them? To figure out their usage we need to understand the functionalities of these objects. Then we’ll go over their usage with some simple examples. Finally, we’ll see the comparison of ViewModel vs ViewData vs ViewBag vs TempData vs Session.

ViewModel

ViewModel in ASP.NET MVC is a strongly typed class which represents the data form one or more data models or data tables to render a specific view in ASP.NET MVC. It can have data form a single source like a table in the database or multiple tables or just a single piece of data or string. Essentially, ViewModel is like a bridge between the model or data and the view in MVC.

The ViewModel represents data in the form of properties optimized for rendering in a view. A single ViewModel object having multiple properties or other child ViewModel. It is populated in the controller and passed to the view template to render in the view. ViewModel can have all the validation rules the required, range, etc. As such, the code in the view is maintainable and clean. As they are strongly types, they provide error checking during compile-time.

Diagrammatic Representation of ViewModel in MVC:

ViewModel Diagram

ViewData

ViewData is an un-typed key-value dictionary derived from the System.Web.Mvc.ViewDataDictionary class. Data is stored as key-value pairs in ViewData. This is used to pass data between controller and view. In controller, the ViewData is filled with the data and retrieved in the view. The life-span of ViewData exists just during the current request. i.e. it starts in the controller and finishes after rendering the view.

ViewData

Example Of ViewData In C#

// Populating ViewData in Controller
public ActionResult Index()
{
    ViewData["SomeKey"] = "Some Data";
    return View();
}

// Retriving ViewData value in the view
@ViewData["SomeKey"].ToString()

ViewBag

ViewBag is a dynamic object which is a wrapper around the ViewData. It is derived from the System.Web.Mvc.ControllerBase.ViewBag Property. As this is a dynamic object, it does not have any properties pre-defined in it. Just like the ViewData, the lifespan of the ViewBag start and ends in the current request. i.e. it starts in the controller and finishes after rendering the view. The ViewBag dynamic object is created and filled with data in the controller by adding a property you wish. The data is retrieved in the view using the same property name.

ViewBag

Example Of ViewBag In C#

// Populating ViewBag in Controller
public ActionResult Index()
{
    ViewBag.SomeProperty = "Some Value";
    return View();
}

// Retriving ViewBag value in the view
@ViewBag.SomeProperty.ToString()

TempData

The TempData object is derived from System.Web.Mvc.TempDataDictionary class. It is an un-typed key-value pair dictionary object. The lifetime of TempData spans from one request to another. I.e. The data persists only when a call is redirected from one action method to another. The object will be automatically destroyed once it is used in the redirected action method. Normally TempData object is used to store and pass small amount of data like error message from one action method to another action method.

In case, if you want to keep the data in the TempData even after the first redirect, then you have to use the TempData.Keep() method to retain the data for further redirection.

TempData stores its contents in ASP.NET Session. So, you should careful while using TempData. Just like sessions, TempData will create problems while using it in webfarm (cluster of servers) environment. You may need to set Session State Mode to Out-of-Process to make it work. It is better to avoid using TempData in webfarm.

Example Of TempData in C#

// Populating TempData in Controller
public ActionResult Index()
{
    TempData["ErrorMsg"] = "Some Error Here";
    return RedirectToAction("Error");
}

// Retriving TempData value in redirected action method
public ActionResult Error()
{
    var msg = TempData["ErrorMsg"];
    // Do Something
} 

Session

Session is also a key-value pair object derived from System.Web.SessionState class. The Session is used to pass data across controllers. The lifespan of a session persists till it’s forcefully destroyed using timeout or by using clear, removeall or abandon methods or when the user closes the browser. As a good practice, try to reduce the usage of session as much as possible. As explained above in TempData, Session is not reliable in webfarm environment. The workaround is to set Session State Mode to Out-of-Process.

Example Of Session In C#

// Populating session
public ActionResult Index()
{
    Session["SomeKey"] = "Some Value";
    return RedirectToAction("Error");
}

// Retriving session value
public ActionResult Error()
{
    var msg = Session["SomeKey"];
    // Do Something
} 

Comparison: ViewModel vs ViewData vs ViewBag vs TempData vs Session

#
ViewModel ViewDataViewBagTempData Session
1Is a class. It is a model specific for rendering a view.Is a key-value dictionary derived from ViewDataDictionary.Is a Dynamic property. It is a wrapper around ViewData.Is a key-value dictionary derived from TempDataDictionary.Is a key-value dictionary derived from TempDataDictionary.
2Strongly typed class. So, no need for type-casting.Un-typed. So, needs type-casting for complex data.Type casting is not required.Un-typed: Needs type-casting for complex data type.Un-typed: Needs type-casting and null checking.
3Represents only the data from a model required for rendering the view.Used to pass data between controller and view.Used to pass data between controller and view.Used to pass data between requests. I.e. it helps to pass data from one controller to another controller.Used to store a small amount of data for the duration of the user visiting the website.
4The lifespan is only for the current request.The lifespan is only for the current request.The lifespan is only for the current request.Lifespan is for the current and subsequent request. The lifespan of TempData can be increased beyond the first redirection using TempData.Keep() method.lifespan of a session persists till it is forcefully destroyed by the server or the user.
5On redirection the ViewModel object will be destroyed.On redirection, the value in the ViewData becomes Null.On redirection, the value in the ViewData becomes Null.The data stored in TempData persists only during redirection.The data stored in Session persists during any number of redirection.
6Provides compile-time error checking and Intellisense support.Does not provide compile-time error checking.Does not provide compile-time error checking.Does not provide compile-time error checking.Does not provide compile-time error checking.
7It is safe to use ViewModel in webfarm (server cluster) environment as they are not dependent on session.ViewData is safe to use in webfarm environment as they are not dependent on session.It is safe to use ViewBag in webfarm environment as they are not dependent on session.TempData is not reliable in webfarm with cluster of servers as the TempData uses ASP.NET Session for storage. The workaround is to set Session State Mode to Out-of-Process and make the data stored in the TempData serializable.Session is not reliable in web farm as they are stored on server’s memory. In a webfarm scenario, if a session is created by a server and the return request goes to another server in the cluster, then the session will be lost. The workaround is to set Session State Mode to Out-of-Process.
8Usage:

(a) Display data in a table with master child relationship.
(b) Reports with aggregate and summary.
(c) Paging data in a table.
(d) Flexible with very simple as well as highly complex data from multiple data-source.

Usage:

(a) To pass a list of data to render a drop down list.
(b) To pass small amount of data to be rendered in the view.
(c) Not ideal for complex data involving multiple data sources.

Usage:

(a) To pass a list of data to render a drop down list.
(b) To pass small amount of data to be rendered in the view.
(c) Not ideal for complex data involving multiple data sources.

Usage:

(a) Useful for storing one time messages like error message and validation messages.
(b) Used in scenarios to pass small data from one action to another action or one controller call to another controller call.

Usage:

(a) To check whether the user is logged in to the website.
(b) To store the user’s permission information.

Conclusion

In my opinion:

  1. Use ViewModel instead of ViewData and ViewBag. As ViewModel provides compile time error checking and intellisense support in Visual Studio IDE, the code will be clean and less error prone.
  2. Use TempData for error handling. On capturing and exception or error, pass the error details using TempData to the error page, to display the proper error details.
  3. Use Session to check the user’s login status and permission level.
  4. Try to avoid using TempData and Session, if your web application is in webfarm environment.

Related Articles

Reference


9 thoughts on “ViewModel vs ViewData vs ViewBag vs TempData vs Session in MVC”

  1. I’m getting nulls across the board when doing either “return RedirectToAction…” or “return Redirect…” after setting Session, TempData, ViewData, and ViewBag. This is local development in a single mvc app.

    Reply
    • Hi,
      The data stored in TempData and session persists during redirection. If the value in TempData or Session is not retained after a redirection, then there could be some other exception causing the session/tempdate to vanish. Please debug and look for any incorrectly captured exceptions.

      Reply
    • I just encounter the case. After judging a long time, I found that it may due to the Chrome couldn’t save the cookie before redirecting for http link. If you change your protocal to https it may work.

      Reply
  2. I have a form that is a two page process, for example, first page you enter username/email, and the next page you can add more info. If you go from second page back to first page, I want that info to still be in the form. But, once you complete the form/click cancel/go to other pages, I want the info you filled in at first page to be gone. Which would be the best to use? I used session variables at first, and check if exist/retrieve it when first page’s controller is loading. But now I’m not sure if that’s best.

    Reply
  3. Great! Let me suggest that It could be interesting to add to this post the implications of usage of these storage areas in distributed scenarios like web farms, where TempData and Session could lead to an exception if they’re set by one server but accessed in a subsequent request from other server.

    Reply

Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.