MVC Razor Html.Partial sub model



我有一个关于MVC Razor中的部分视图的问题。非常感谢任何帮助,这很可能是我错过的东西,但我在搜索时找不到复制相同问题的任何内容。

所以我将我的视图绑定到视图模型。

public class Person
{
    public string Name { get; set; }
    public virtual ContactInformation ContactInformation { get; set; }
}

然后我有一个部分视图来呈现联系信息模型。

<div>
    @Model.Name
</div>
<div>
    @Html.Partial("_ContactInformation", Model.ContactInformation)
</div>

但是,"_ContactInformation"视图在<input>name 属性中呈现时没有联系人信息

通常 razor 将 name 属性绑定到类似的东西:name="ContactInformation.Address"。但由于它是部分的,因此它被呈现为 name="Address"。

我是否错过了某些内容,或者这是它工作的预期方式?

您有两个选择。选项 1 - 显式指定前缀:

@Html.Partial("_ContactInformation", Model.ContactInformation, new ViewDataDictionary
{
    TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = "ContactInformation" }
})

选项 2 是将部分视图转换为模型的编辑器模板,而不是使用EditorFor帮助程序方法,该方法应该能够为您添加前缀:

@Html.EditorFor(m => m.ContactInformation)

最新更新