Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Differences between ViewData, ViewBag, Session and TempData

Posted on: 2012-02-17

These three mechanisms transport information from one page to the other. ViewData and View bag can be threat in the same group because they are both the same thing. The ViewBag is an object that use ViewData. The main difference is that it's possible to access the values from dynamic properties instead of accessing from an array with a string key.

 ViewData["Name"] = "Patrick"; //Or ViewBag.Name = "Patrick"; 

So, in fact, we are storing an object value into a dictionary which is defined to have Object type value and string key.

TempData is also a dictionary of string key and object value. The difference is that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it's in the same HTTP Request.

 TempData["Name"] = "Patrick"; 

The ViewData and ViewBag won't have any value after a redirection. This is because their goal is to provide a way to communicate between controllers and views. It's a communication mechanism within the server call. The life cycle of the ViewData and ViewBag is shorter than TempData.

The last mechanism is the Session which work like the ViewData, like a Dictionary that take a string for key and object for value. This one is stored into the client Cookie and can be used for a much more long time. It also need more verification to never have any confidential information.