ViewData vs ViewBag vs TempData vs Session

ASP.NET MVC offers us four options ViewData, VieBag, TempData and Session for passing data from controller to view and in next request. But now question is that what is the differences between these different type. In this article I have described these differences.

ViewData

  • Used to pass data from controller to corresponding view.
  • ViewData is property of ControllerBase class.
  • ViewData is a dictionary object that is derived from ViewDataDictionary class.
  • Life lies only during the current request.
  • If redirection occurs then it’s value becomes null.
  • It’s required typecasting for getting data and check for null values to avoid error.
Syntax:

ViewData["Message"] = "Data has been saved successfully!"

ViewBag

  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  • Used to pass data from controller to corresponding view.
  • ViewBag is property of ControllerBase class.
  • Life also lies only during the current request.
  • If redirection occurs then it’s value becomes null.
  • It doesn’t required typecasting for getting data.
Syntax:

ViewBag.Message = "Data has been saved successfully!"

TempData

  • TempData is dictionary object that is derived from TempDataDictionary class and stored in short lives session.
  • TempData is property of ControllerBase class.
  • Used to pass data from current request to subsequent request (means redirecting from one page to another).
  • Life is very short and lies only till the target view is fully loaded.
  • It’s required typecasting for getting data and check for null values to avoid error.
Syntax:

TempData["Message"] = "Data has been saved successfully!"

Session

  • Session is an object that is derived from HttpSessionState class.
  • Session is a property of HttpContext class.
  • Session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it never expires.
  • Session is valid for all requests, not for a single redirect.
  • It’s required typecasting for getting data and check for null values to avoid error.
Syntax:

Session("Message") = "Data has been saved successfully!"