Newbie ASP.NET MVC question:
I have the following model:
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
}
And the following view for customer:
<% using (Html.BeginForm()) { %>
First Name: <%=Html.TextBox("FirstName") %>
Last Name: <%=Html.TextBox("LastName") %>
<% Html.RenderPartial("AddressView", Model.Address); %>
<input type="submit" name="btnSubmit" value="Submit"/>
<%} %>
And the following partial view for Address:
<%=Html.DropDownList("CountryId", new SelectList(Country.GetAll(), "Id", "Name") })%>
<%=Html.DropDownList("CountrySubdivisionId", new SelectList(CountrySubDivision.GetByCountryId(Model.CountryId), "Id", "Name"))%>
And the following controller action:
[AcceptVerbs(HttpVerbs.Post)]
public ViewResult Index(Customer customer, Address address)
{
customer.Address = address;
ViewData.Model = customer;
return View();
}
I was hoping that the action would work with 1 parameter: customer, and that I would not have to reassign customer.Address manually. However, when the action is executed, Customer.Address is null.
Am I using model binding incorrectly, or does my action require separate parameters for Customer and Address?
Use Html.EditorFor instead of Html.RenderPartial.
See Model binding with nested child models and PartialViews in ASP.NET MVC.