MVC Razor Html.Partial sub model

梦想的初衷 提交于 2019-12-25 01:22:49

问题


I have a problem concerning Partial views in MVC Razor. Any help is highly appreciated, it's most likely something I've missed, but I could find nothing while searching that had the same problem replicated.

So I'm binding my view to a view model.

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

    public virtual ContactInformation ContactInformation { get; set; }
}

And then I have a view with a partial to render the contact information model.

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

However, the "_ContactInformation" view is rendered without ContactInformation in the nameattribute of the <input>s

Usually razor binds the name attribute to something like: name="ContactInformation.Address". But since it's a partial it gets rendered as name="Address".

Am I missing something or is this the intended way for it to work?


回答1:


You have two options. Option 1 - specify the prefix explicitly:

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

Options 2 is to turn partial view into an editor template for your model and than use EditorFor helper method, that should be able to add prefixes for you:

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


来源:https://stackoverflow.com/questions/27234463/mvc-razor-html-partial-sub-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!