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

 

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.

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.

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

ViewData

ViewBag

TempData

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.
7
Usage:

(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, so as to render the appropriate error details.
  3. Use Session to check the user’s login status and permission level.

Reference

 

Leave your thoughts...