When passing additional data from an ASP.NET MVC Controller to a View there are several options that are available, you can pass one, two or basically any combination of the below:

  • ViewBag
  • ViewData
  • TempData

So which one do you use?. Well, before answering that question let’s have a quick look at what each one of them are and how you can benefit from them.

ViewBag

ViewBag is a dynamic object, which means that you can add to it anything that you please (strongly typed objects, primitive values, etc). This sounds really cool !

ViewData

ViewData is a ViewDataDictionary, kind of a dictionary of objects that can be accessed via a key (string). As ViewData also hold objects it is considered very similar to the ViewBag but it differs from it in that you need to do typecasting in order to get the original object back (and you’ll obviously need to check for null references before accessing its properties).

The following example will help clarify the above. Let’s say you want to pass some data from a Controller to its View and you decide to take advantage of ViewBag and ViewData to achieve this:

 

And now let’s get the data back from the View:

See the difference ? you can use either of them but make sure that with ViewData you do typecasting and check for nulls.

 

TempData

As with the ViewData, TempData is also a Dictionary (a TempDataDictionary to be precise) so you could add an object to it an access it via its key (correct!, doing typecasting and always checking for null references), the difference with ViewData is that TempData keeps its data for the duration of the HTTP request so its  useful when passing data between requests (for instances when a redirection occurs)

 

The following example shows how we store an object inside TempData and then retrieve it after a redirection has taken place

 

Hope this helps someone out there, if you have any questions or feedback please fill out the below form and I’ll get back to you pretty quickly !

 

cheers

Harold