View Models

Often a view needs to display a variety of data that doesn't map directly to a domain model. For example, you might have a view meant to display details about an individual product. But that same view also displays other information that's ancillary to the product such as the name of the currently logged-in user, whether that user's allowed to edit the product or not, and so on.

One easy approach to displaying extra data that isn't a part of your view's main model is to simply stick that data in the ViewBag. It certainly gets the job done and provides a flexible approach to displaying data within a view.

But it's not for everyone. You may want to tightly control the data that flows into your view and have it all be strongly typed so your view authors can take advantage of IntelliSense.

One approach you might take is to write a custom view model class. You can think of a view model as a model that exists just to supply information for a view. Note that the way I use the term “view model” here is different from the concept of view model within the Model View ViewModel (MVVM) pattern. That's why I tend to use the term “view specific model” when I discuss view models.

For example, if you had a shopping cart summary page that needed to display a list of products, the total cost for the cart, and a message to the user, you could create the ShoppingCartSummaryViewModel class, shown as follows:

 public class ShoppingCartViewModel { public IEnumerable<Product> Products { ...

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.