MVC4部分视图未在回发时将值加载到“容器”模型中

时间:2012-05-20 07:07:24

标签: asp.net-mvc

所以我想创建一个可重复使用的视图来编辑地址,电话号码等。

我设置了一个包含所需模型的容器模型。 创建了一个局部视图来处理地址部分 表格

但是当它回发到控制器时,主页上有客户数据,但部分视图中的任何内容都不存在(使用MVC4 / Razor)

容器模型

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; }
}

控制器:

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);
}

主要观点:

@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.TemplateInfo { HtmlFieldPrefix = "Main" }
        })

        ...        

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}
.....

地址部分视图:

@model ProjectName.Business.Address

<fieldset style="margin-top:  20px;">
    <legend>@(ViewData["label"] ?? "Address")</legend>

    @Html.HiddenFor(model => model.AddressId)

    <div class="editor-label">
        @Html.LabelFor(model => model.Street)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Street)
        @Html.ValidationMessageFor(model => model.Street)
    </div>
    ...
</fieldset>

我在这里做错了什么 - 为什么我不能从部分视图填充模型?

1 个答案:

答案 0 :(得分:12)

解决了!我想通了!无法入睡,只是偶然发现它!

在视图中,您必须确保HtmlFieldPrefix使用与复合模型类中相同的名称,因此我将这两个地址命名为“MainAddress”和“ShippingAddress” - 只需确保相同的名称是在设置Partial时使用:

@Html.Partial("Address", Model.MainAddress, new ViewDataDictionary(Html.ViewDataContainer.ViewData) {
    TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = "MainAddress" }
})

@Html.Partial("Address", Model.ShippingAddress, new ViewDataDictionary(Html.ViewDataContainer.ViewData) {
    TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = "ShippingAddress" }
})