ViewData vs ViewBag vs TempData vs Session

In ASP.NET MVC there are three ways – ViewData, ViewBag and TempData to pass data from controller to view and in next request. Like WebForm, you can also use Session to persist data during a user session.

ViewData

  • ViewData is a dictionary object that is derived from ViewDataDictionary
  • ViewData is a property of ControllerBase class.
  • ViewData is used to pass data from controller to corresponding view.
  • It’s 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.

TempData

  • TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
  • TempData is a property of ControllerBase class.
  • TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
  • It’s 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 is used to store only one time messages like error messages, validation messages.

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.
  • ViewBag is a property of ControllerBase class.
  • It’s 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.

Session

  • In ASP.NET MVC, Session is a property of Controller class whose type is HttpSessionStateBase.
  • Session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it persists for its expiration time (by default session expiration time is 20 minutes but it can be increased).
  • Session is valid for all requests, not for a single redirect.
  • It’s also required typecasting for getting data and check for null values to avoid error.
0 0 votes
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x