Should I reassign partial view data back to the model when sending POST back to my controller?

New 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 the client:

<% 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 the 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: the client, and that I would not have to reassign the .Address client manually. However, when the action is executed, Customer.Address is null.

Am I using the wrong model binding or does my action require separate parameters for the client and address?

+3
source share
3 answers

Use Html.EditorFor instead of Html.RenderPartial.

. PartialViews ASP.NET MVC.

+2

, Address (). Partial View

//Here the Model refers to Model.Address in the PartialView
<%=Html.TextBox("Address.property1", Model.property1) %>

, ModelBinder , .

EDIT: :

<%=Html.DropDownList("Address.CountryId", new SelectList(Country.GetAll(), "Id", "Name") })%>
<%=Html.DropDownList("Address.CountrySubdivisionId", new SelectList(CountrySubDivision.GetByCountryId(Model.CountryId), "Id", "Name"))%>
+2

POST . , .

The only thing he sees is the POSTED HTML form. You can see this in Firebug or Fiddler. That way, you can only have one argument Customerfor action POSTif the form has the correct key names and values.

There are many rules about this, but the answer to your question is that the fact that you used a partial view does not affect the binding of the model to POST. The only thing that matters is the contents of the form.

+2
source

Source: https://habr.com/ru/post/1725854/


All Articles