What a View Does

The view is responsible for providing the user interface (UI) to the user. It is given a reference to the model, and it transforms that model into a format ready to be presented to the user. In ASP.NET MVC, this consists of examining the ViewDataDictionary handed off to it by the Controller (accessed via the ViewData property) and transforming the contents of that to HTML.


Not all views render HTML. HTML is certainly the most common case when building web applications. HTML is the language of the web. But as the section on action results later in this chapter points out, views can render other content types as well.

Starting in ASP.NET MVC 3, view data can also be accessed via the ViewBag property. ViewBag is a dynamic property that provides a convenient syntax for accessing the same data accessible via the ViewData property. It's effectively a wrapper over ViewData that takes advantage of the new dynamic keyword in C# 4. This allows using property accessor-like syntax to retrieve values from a dictionary.

Thus ViewBag.Message is equivalent to ViewData[“Message”].

For the most part, there isn't a real technical advantage to choosing one syntax over the other. ViewBag is just syntactic sugar that some people prefer over the dictionary syntax.


While there isn't ...

Get Professional ASP.NET MVC 3 now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.