Wednesday, February 22, 2012

ASP.Net MVC 3 - passing data to view by ViewBag, ViewData, and TempData

      ViewBag, ViewData, and TempData are 3 vehicles to pass data from action method to a view. But it's confusing what the differences are between them and when to use which method to pass the data to view. I would like to share my understanding of this topic.

       1. ViewBag:

              ViewBag is a new feature introduced with MVC 3. This feature allows you to define any property on a dynamic object, which can be accessed through the Controller.ViewBag property in a view. And the better thing is you don't have to cast the property.

       2. ViewData:

              ViewData is similar to ViewBag, but it derives from ViewDataDictionary class. So you access the data by key/value style and have to cast the value to known type. The casting make ViewData less attractive comparing with ViewBag.

       3. TempData:

              TempData is similar to Session data. But the life of TempData is much shorter than Session. It lasts only one more request and will be marked for deletion once it is read. So TempData is usually used to keep the data across a redirection.

No comments: