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:

UnFigure
public class ShoppingCartViewModel {
    public IEnumerable<Product> Products { get; set; }
    public decimal CartTotal { get; set; }
    public string Message { get; set; }
}

Code snippet 3-12.txt

Now you can strongly type a view to this model, using the following @model directive:

@model ShoppingCartSummaryViewModel

Code snippet 3-13.txt

This gives you the benefits of a strongly typed view (including type checking, IntelliSense, and freedom from having to cast untyped ViewDataDictionary objects) without requiring any changes to the Model classes.

To see an example of this shopping cart view model, run the following command in NuGet:

UnFigure
Install-Package Wrox.ProMvc3.Views.ViewModel
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.59.145