tags:

views:

62

answers:

2

The name "view model" suggests that it models the data for the view. That much is obvious. What else can or should go in the view model?

As an example, a view might display a list of items in a shopping cart, fields for customer's credit card info, and fields for customer's billing information. The view model might contain properties for all that OR it might only contain properties for the shopping cart items.

+2  A: 

The view model is a class that represents the fields that your view shows/modifies. So for example if you are going to show a shopping cart and customer's credit card all on the same page these properties should all belong to the view model.

You could even put properties like this in your view model if the view is going to show a drop down list of day names:

public IEnumerable<SelectListItem> DayNames
{
    get
    {
        return CultureInfo
            .CurrentCulture
            .DateTimeFormat
            .DayNames
            .Select((dayName, index) => new SelectListItem 
            { 
                Value = index.ToString(),
                Text = dayName
            });
    }
}
Darin Dimitrov
What about input fields that start out empty? That data will be given via modelbinder to a submit action. Does that mean the submit action ought to receive a view model?
Byron Sommardahl
Yes, the submit action should receive a view model that will be mapped to a domain model which will be handled to the data access layer.
Darin Dimitrov
+1  A: 

How exactly you use your view models is a judgement call. One developer might have fewer typed ViewModels so they can be reused. Another developer might have more ViewModels, each smaller and more specific to particular actions. And another developer might rely more on ViewData.

If possible, have your view models be well-organized, contain just what the view needs, and consist mostly of light entity objects. If you have a complicated view though, don't be afraid to make a highly customized view model class that will help simplify the view logic. It's okay to make reusable ViewModels that have a little unused data in them, but avoid using just a few one-size-fits-all ViewModels. ViewModels should have just the data needed for that view or very close.

Patrick Karcher