ViewData, ViewBag, TempData in MVC

In MVC there are three ways - ViewData, ViewBag and TempData to pass data from controller to view.

ViewData
  •  ViewData is a dictionary object that is derived from ViewDataDictionary class. public 
  •  ViewData is used to pass data from controller to corresponding view.
  •  Its life lies only during the current request.
  •  If redirection occurs then its value becomes null.
  •  It’s required typecasting for getting data and check for null values to avoid error.

ViewBag

  •  ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  •  Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
  • Its life also lies only during the current request.
  • If redirection occurs then its value becomes null.
TempData
  • TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
  • TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
  • Its 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.
  • It’s used to store only one time messages like error messages, validation messages.

Post a Comment