Reputation: 717
I’m trying to put a partial view in a regular view that is not of the same type. I create the partial view from my Assignment model and put it in the /Views/Shared folder. Then I tried to call the partial view in a regular view that was based on another model (InstructorIndexData ) and got the error message:
The model item passed into the dictionary is of type 'SchoolIn.ViewModels.InstructorIndexData', but this dictionary requires a model item of type 'SchoolIn.Models.Assignment'.
Here’s a bit of code from the partial view:
@model ...Models.Assignment
<div class="display-label">Grade</div>
<div class="display-field">
@Html.DisplayFor(model => model.Grade)
</div>
And here’s a bit of code from the regular view:
@model SchoolIn.ViewModels.InstructorIndexData
<td> @Html.Partial("_UpdateAttendance")</td>
How can I put a partial view of one type into a regular view of another type? Thanks for any help.
Upvotes: 0
Views: 258
Reputation: 1038950
If you are rendering the view using the Html.Partial
method you could pass the model as second argument:
@Html.Partial("_PartialName", item.Grade)
If you are using display/editor templates, this is done automatically:
@Html.DisplayFor(x => x.Grade)
Now assuming that the Grade property is of type Assignment
, then the ~/Views/Shared/DislpayTemplates/Assignment.cshtml
will be rendered.
If on the other hand you have a collection property:
public IEnumerable<Assignment> Grades { get; set; }
then you could use:
@model SchoolIn.ViewModels.InstructorIndexData
<table>
<tr>
@Html.DisplayFor(x => x.Grades)
</tr>
</table>
and now the Assignment.cshtml
display template will automatically be rendered for each element of the Grades collection so that you don't have to write any ugly loops in your view.
Upvotes: 1