Virtual Classes Logo          Virtual Classes
    Read Anytime,Anywhere


ASP.NET MVC offers us three options - ViewData, ViewBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar but TempData is bit different then these two.

ViewData In MVC

ViewData is used to transfer data from controller to view,it's life lies only in current request. It's value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. ViewData is a dictionary of object and it is accessible by a key.
ViewData is property of controller that exposes an instance of the ViewDataDictionary class.
ViewData is introduced in MVC 1.0 and available in MVC 1.0 and above.
Example of ViewData-
Setting ViewData value in Controller- Use of ViewData in Controller

Using ViewData value in view- Use of ViewData in View

ViewBag in MVC

ViewBag is also used to transfer data from controller to view and life lies only in current request.
ViewBag is a dynamic property,ViewBag is able to set and get value dynamically and able to add any number of additional fields without converts it to strongly typed.In simple word, ViewBag is just a wrapper around the ViewData. ViewBag is introduced in MVC 3.0 and available in MVC 3.0 and above.
Example of ViewBag-
Setting ViewBag value in Controller- Use of ViewBag in Controller

Using ViewBag value in view- Use of ViewBag in Viewbag

TempData in MVC

TempData is used to transfer data between controllers or between actions.
It helps to maintain data when you move from one controller to other controller or from one action to other action. TempData internally use Session variables and it is used to store only one time messages like error messages, validation messages. TempData is also a dictionary same as ViewData and it is derived from TempDataDictionary class.
TempData stores data for short time,it keep data for the time of HTTP Request it mean that it hold data between two consecutive requests.
With the help of TempData.Keep() method we can keep value in TempData object after request completion.
TempData is also introduced in MVC1.0 and available in MVC 1.0 and above.
Example of TempData-
Setting TempData value in Controller- Use of TempData in Controller

Using TempData value in view- Use of TempData in view