If you are learning ASP.NET MVC 3 or curious as to the new features in ASP.NET MVC 3, you can check out my list of ASP.NET MVC 3 Tutorials.
ViewBag in ASP.NET MVC 3
If you have been using ASP.NET MVC and ViewData, you should be pretty comfortable with the new ViewBag introduced in ASP.NET MVC 3. ViewBag is nothing more than a convenient wrapper to make it easier to store and retrieve key/value pairs in the backing store used by ViewData.
For example, when you store a message in ViewData in the controller using ViewData[”Message”] = “Welcome to ASP.NET MVC”, you can display the message in your view using @ViewBag.Message. And the opposite is true. Store the message in your controller as ViewBag.Message = “Welcome to ASP.NET MVC”, and you can retrieve it in the view using @ViewData[”Message”]. They are one in the same. ViewBag is just a dynamic wrapper around the same data, allowing you to access it in a more convenient manner.
Here is an example of a controller using the new ViewBag to store data.

I can then access those items the same way in the view.

One of the cool benefits of using ViewBag over ViewData is we don't have to cast ViewBag.Date to DateTime, ViewBag.Post to Post, and ViewBag.Tags to a string array before using them as such. This cuts down on the noise in the view.
No Intellisense Support for ViewBag
What catches people off guard is that there is no intellisense support for ViewBag. When using the ViewBag in the view you will not get a list of properties you specified in the controller. ViewBag is of type dynamic, and you don't get intellisense on dynamic types. You don't get intellisense with ViewData either, so you aren't losing anything.
Can't Pass Dynamic Types to HtmlHelpers (aka Extension Methods)
There is also another gotcha in that you can't pass dynamic types into Extension Methods (aka HtmlHelpers). If you do so, you will get an error like:
'System.Web.Mvc.HtmlHelper' has no applicable method named '[xyz]' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
In order to get around this error you will need to cast the arguments to their proper type before sending them to the extension method. This could re-add some of the casting noise you were hoping to avoid by using the ViewBag instead of ViewData.
Conclusion
Hopefully this helps you understand the ViewBag introduced in ASP.NET MVC 3. Key thing to remember is that it is just a different way of accessing the same backing store used by ViewData.
Hope this helps.
David Hayden
Related Posts: