Data Haunting

Easy Solutions Destination

By

ViewBag, ViewData and TempData in Asp.net MVC

In Asp.net MVC we can pass data from controller to view and controller(action) to controller(action) in next request using ViewBag, ViewData and TempData but all these three properties have different meaning in different scenario. In this article we will discuss difference between ViewBag, ViewData and TempData in MVC and when to use these three properties.

Key difference between ViewBag, ViewData and TempData

Below table can help you to understand behavior of ViewBag, ViewData and TempData plus which one you have to use while working with Asp.net MVC.

Property Controller to View Controller to Controller View to Controller
ViewBag YES NO NO
ViewData YES NO NO
TempData YES YES YES
HiddenField/Query String NO NO YES

Now we will discuss all these properties in Details.

ViewData

  1. ViewData can be used when you want to pass data from Controller to View.
  2. ViewData is a Property of ControllerBase class
  3. ViewData is a dictionary object which is derived from ViewDataDictionary class.
  4. ViewData’s life is only for current request, when redirection occurs then it’s value becomes null.
  5. ViewData required type casting as well need to check for null value to avoid error.
  6. Example :

ViewBag

  1. ViewBag can be used when you want to pass data from Controller to View
  2. ViewBag is a Property of ControllerBase class
  3. ViewBag is a dynamic property which takes advantage of new dynamic feature of c# 4.0
  4. ViewBag is a basically wrapper around ViewData to pass data dynamically from controller to view
  5. ViewBag’s life is only for current request, when redirection occurs then it’s value becomes null.
  6. ViewBag does not required type casting as well does not need to check for null value.
  7. Example :

TempData

  1. TempData can be used when you want to pass data from Controller to Controller.
  2. TempData is used to pass data from current request to subsequent request(from one page to another page).
  3. TempData is a Property of ControllerBase class.
  4. TempData is a dictionary object of TempDataDictionary class and works as a short live session.
  5. TempData’s life is short and lies only when next request occured.
  6. TempData required type casting as well need to check for null value to avoid error.
  7. TempData can be used for passing error message and so like.
  8. TempData value can be persist using keep and peek method. You can refer How to persist TempData value using Keep and Peek method.
  9. Example :

What is your opinion ?

Here we have compared viewbag vs viewdata vs tempdata in MVC and learnt when to use ViewBag, ViewData and TempData. I hope it will be very useful to you understand difference between viewbag, viewdata and tempdata. If you have any query you can comment or you can mail me.

Leave a Reply