MVC Razor Html.Partial sub model

2019-09-01 05:56发布

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条回答
时光不老,我们不散
2楼-- · 2019-09-01 06:40

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)
查看更多
登录 后发表回答