Strongly Typed Views

Suppose you need to write a view that displays a list of Album instances. One possible approach is to simply add the albums to the view data dictionary (via the ViewBag property) and iterate over them from within the view.

For example, the code in your Controller action might look like this:

public ActionResult List() {
 var albums = new List<Album>();
 for(int i = 0; i < 10; i++) {
   albums.Add(new Album {Title = "Product " + i});
 }
 ViewBag.Albums = albums;
 return View();
}

In your view, you can then iterate and display the products, as follows:

<ul>
@foreach (Album a in (ViewBag.Albums as IEnumerable<Album>)) {
 <li>@a.Title</li>
}
</ul>

Notice that we needed to cast ViewBag.Albums (which is dynamic) to an IEnumerable<Album> before enumerating it. We could have also used the dynamic keyword here to clean the view code up, but we would have lost the benefit of IntelliSense when accessing the properties of each Album object.

<ul>
@foreach (dynamic p in ViewBag.Albums) {
 <li>@p.Title</li>
}
</ul>

It would be nice to have the clean syntax afforded by the dynamic example without losing the benefits of strong typing and compile-time checking of things such as correctly typed property and method names. This is where strongly typed views come in.

Remember that ViewData is a ViewDataDictionary, not just a generic Dictionary. One reason for this is that it has an additional Model property to allow for a specific model object to be available to the view. Since there can ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.