代码之家  ›  专栏  ›  技术社区  ›  Josh Kodroff

当发回我的控制器时,我是否必须重新分配一个部分视图的数据回模型?

  •  3
  • Josh Kodroff  · 技术社区  · 16 年前

    新手ASP.NET MVC问题:

    我有以下型号:

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Address Address { get; set; }
    }
    

    以及客户的以下视图:

    <% 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"/>
    <%} %>
    

    以及以下地址部分视图:

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

    以及以下控制器动作:

        [AcceptVerbs(HttpVerbs.Post)]
        public ViewResult Index(Customer customer, Address address)
        {
            customer.Address = address;
            ViewData.Model = customer;
            return View();
        }
    

    我希望该操作可以与1个参数一起使用:customer,并且不必重新分配customer.address。但是,执行操作时,customer.address为空。

    我是否错误地使用模型绑定,或者我的操作需要客户和地址的单独参数?

    3 回复  |  直到 15 年前
        1
  •  2
  •   Community Mohan Dere    9 年前

    使用html.editorfor代替html.renderpartial。

    Model binding with nested child models and PartialViews in ASP.NET MVC .

        2
  •  2
  •   Craig Stuntz    16 年前

    这个 POST 行动根本不了解这种观点。它不知道也不关心是否涉及到部分观点。

    这个 只有 它看到的是已发布的HTML表单。你可以在Firebug或Fiddler中看到这个。所以你只能吃一个 Customer 论据 行动 如果 表单具有正确的键名和值。

    关于这一点,有很多规则,但您的问题的答案是,使用局部视图对绑定到日志的模型没有任何影响。唯一重要的是表单的内容。

        3
  •  2
  •   JOBG    16 年前

    它应该绑定到客户,因为客户定义了地址属性类型(地址)。 地址部分视图应定义如下名称:

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

    这样,ModelBinder就知道地址属性应该绑定到客户对象的地址属性部分。

    编辑:向元素名称添加地址:

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