Michael Pryor
Michael Pryor

Reputation: 25346

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 SelectList 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?

Upvotes: 3

Views: 1317

Answers (1)

Anubis
Anubis

Reputation: 2624

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

Upvotes: 5

Related Questions