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:

UnFigure
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();
}

Code snippet 3-6.txt

In your view, you can then iterate and display the products like so:

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

Code snippet 3-7.txt

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.

<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.

In the Controller method, you can specify the model via an overload of the View method whereby you pass in the model instance: ...

Get Professional ASP.NET MVC 3 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.