What is the difference among ViewBag, ViewData and TempData ?

Jak
Jak
Member
364 Points
152 Posts

hi.

What is the difference among ViewBag, ViewData and TempData ?

Views: 8209
Total Answered: 1
Total Marked As Answer: 1
Posted On: 11-Nov-2014 03:31

Share:   fb twitter linkedin
Answers
Nice One
Nice One
Member
110 Points
10 Posts
         

In ASP.NET MVC there are three ways (ViewData, ViewBag and TempData) to pass data from Controller to View and in next request.

ViewData:

  • ViewData is a dictionary object that is derived from ViewDataDictionary class.
  • public ViewDataDictionary ViewData { get; set; }
  • 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.

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.
  • public Object ViewBag { get; }
  • 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.

TempData:

  • TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
  • public TempDataDictionary TempData { get; set; }
  • 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.

 

Posted On: 08-Dec-2014 23:40
 Log In to Chat