开发者

What kind of data belongs in a view model?

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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜