开发者

How do you call UpdateModel when you use a ViewModel class?

In MVC3, it seems that the default way to show properties of a model in your view is like so:

@Html.DisplayFor(model => model.Title)

This works fine if your model matches your object exactly. But if you define a custom ViewModel, for example like in the NerdDinner tutorial

public class DinnerFormViewModel {

  // Properties
  public Dinner     Dinner    { get; private set; }
  public SelectL开发者_开发问答ist Countries { get; private set; }

  // Constructor
  public DinnerFormViewModel(Dinner dinner) {
    Dinner = dinner;
    Countries = new SelectList(PhoneValidator.AllCountries, dinner.Country);
  }
}

Then your DisplayFor code would look like:

@Html.DisplayFor(model => model.Dinner.Title)

Which means the names of the form items are Dinner.Title instead of just Title, so if you call UpdateModel in your Action code, MVC won't "see" the properties it needs to see to update your Dinner class.

Is there a standard way of dealing with ViewModels that I'm overlooking for this scenario in MVC3?


Use the 'prefix' parameter for UpdateModel method

UpdateModel(model.Dinner, "Dinner");

and if you need to update a specified properties only - use something like this

UpdateModel(model.Dinner, "Dinner", new []{"Title"});

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜