问题
I have an _Address partial view. This partial view contains all of the address fields that match the Address Model. At the top of this view I set the model like this:
@model Data.Address
In my CustomerInfo view I try the following to render the Address fields as part of my form:
@Html.Partial("~/Views/Shared/Partial/_Address.cshtml")
The error I am getting is:
The model item passed into the dictionary is of type 'Data.Customer', but this dictionary requires a model item of type 'Data.Address'.
I am assuming I am getting this error because the model declared in my CustomerInfo view is of type Data.Customer and it is automatically trying to pass it to my _Address view which has a model of type Data.Address in it.
What is the proper way to make this flow properly? I noticed there is also an @Html.RenderPartial("ViewName", model) helper but have no idea how to pass it Data.Address since the primary model in my CustomerInfo view is Data.Customer.
回答1:
I guess that your primary model Data.Customer
already has one or more properties of type Data.Address
that you would like to display. So you would use the @Html.Partial
helper and pass the value of this property like that:
@Html.Partial("ViewName", Model.SomeAddressProperty)
As an alternative to using the Html.Partial
helper you could use Editor/Display templates. They work by convention. So rename your _Address.cshtml
partial to ~/Views/Shared/EditorTemplates/Address.cshtml
and then inside your main view use:
@Html.EditorFor(x => x.SomeAddressProperty)
or if the partial doesn't contain input fields or forms you could use a display template: ~/Views/Shared/DisplayTemplates/Address.cshtml
and then:
@Html.DisplayFor(x => x.SomeAddressProperty)
The convention here is the name and location of the template. Since the type of the SomeAddressProperty
is Address
, ASP.NET MVC will look for the corresponding Address.cshtml
template.
If your main view model doesn't have an address property you should simply go ahead and add one or more such properties and populate them in the controller action rendering the main view. Then you can call the partial for each of those properties.
回答2:
First of all, don't pass Data.Customer
to your main view, but only 'Data'. This is more flexible, all your have to do then is fix the references inside the main view, so instead of @Model.FirstName
, you use @Model.Customer.FirstName
. This way, you can call your partial view with a more explicit @Html.Partial("~/Views/Shared/Partial/_Address.cshtml", @Model.Address)
.
来源:https://stackoverflow.com/questions/28519520/passing-a-model-to-a-partial-view