9
So I want to create a re-usable view for editing an Address, phone number, etc.
I setup a Container Model that contains all the Models needed. Created a partial view to handle the Address part of th e form
But when it posts back to the controller, customer data is there from the main page, but anything from the partial views is not there (using MVC4/Razor)
Container Model
public class CustomerViewModel {
public Customer CustomerData { get; set; }
public Address MainAddress { get; set; }
public Address ShippingAddress { get; set; }
public Phone MainPhone { get; set; }
public Phone Fax { get; set; }
}
Controller:
public ActionResult Edit(int id = 0) {
CustomerViewModel model = new CustomerViewModel();
model.CustomerData = Customer.FetchById(id);
if (model.CustomerData == null) return HttpNotFound();
//... load addresses, phones
return View(model);
}
[HttpPost]
public ActionResult Edit(CustomerViewModel model) {
if (ModelState.IsValid) {
///... save everything here - model has CustomerData, but nothing else
}
return View(model);
}
Main View:
@model ProjectName.WebSite.Models.CustomerViewModel
.....
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Customer</legend>
@Html.HiddenFor(model => model.ModelCustomer.CustomerId)
<div class="editor-label">
@Html.LabelFor(model => model.ModelCustomer.CompanyName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ModelCustomer.CompanyName)
@Html.ValidationMessageFor(model => model.ModelCustomer.CompanyName)
</div>
...
@Html.Partial("Address", Model.MainAddress, new ViewDataDictionary {
TemplateInfo = new System.Web.Mvc.TemplateIn