views:

37

answers:

1

I have the following nested viewmodel class...

public class CustomerModel
{
  public string name;
  public Address mailingAddress;
  public Address billingAddress;
}

public class Address
{
  public string line1;
  public string city;
  public string country;
}

I was hoping that there is some automated way to create an edit page, but everything that I've tried and read indicates that the framework and code-generates only handle top level properties in your viewmodel. The 'name' property is the only one generated in the view and in the action, it is only the 'name' property that is populated with the addresses being left as null.

[HttpPost]
public ActionResult Edit(CustomerModel model)

however, if i manually add input boxes for the address (through partial views) and switch over to the FormCollection signature for the action, i get the appropriate address values entered on the screen.

is there any easy solution for this other than creating my own function to convert from FormCollection to CustomerModel?

A: 

Could you use an editor template here? Basically, you create a strongly typed partial view (Address is the type in your case), store it in a specific folder (/Views/Shared/EditorTemplates) and whenever an editor is rendered for a member of that data type, the partial view is automagically rendered instead. So, calling Html.EditorFor(model => model.mailingAddress) renders the partial view instead.

I think the first place I read about this was when I was looking for some DateTime validation. Check out this link, and maybe your partial view will have some Html.EditorFor(model => model.line1)'s and Html.EditorFor(model => model.city)'s

This does not make everything super-automatic, but it helps with the future editing of data types like Address.

David