Reputation: 3969
I'd like a partial view to be rendered within a view and since I use strongly typed views I'll require two view models to be included within the main view.
Here's my view model that contains the model the partial view uses and the one the main view uses:
public class PersonIndexViewModel
{
public PersonLookupViewModel PersonLookupViewModel { get; set; }
public List<PersonViewModel> PersonViewModel { get; set; }
}
And here's the view that utilises it all:
@model ViewModels.PersonIndexViewModel
@{
ViewBag.Title = "Registered People";
}
<h2>@ViewBag.Title</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
@Html.Partial("_LookupPartial", Model.PersonLookupViewModel);
<table>
<tr>
<th>
@Html.DisplayNameFor(m => m.PersonViewModel.personName)
</th>
<th>
@Html.DisplayNameFor(m => m.PersonViewModel.dob)
</th>
<th>
@Html.DisplayNameFor(m => m.PersonViewModel.address)
</th>
<th>
@Html.DisplayNameFor(m => m.PersonViewModel.internalNo)
</th>
</tr>
@foreach (var item in Model.PersonViewModel) {
<tr>
<td>
@Html.DisplayFor(i => i.PersonViewModel.personName)
</td>
<td>
@Html.DisplayFor(i => i.PersonViewModel.dob)
</td>
<td>
@Html.DisplayFor(i => i.PersonViewModel.address)
</td>
<td>
@Html.DisplayFor(i => i.PersonViewModel.internalNo)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.id })
</td>
</tr>
}
</table>
So my problem is that because PersonViewModel
is a list it seems the expressions above can't access their properties. For example below personName
is not recognised.
@Html.DisplayNameFor(m => m.PersonViewModel.personName)
Upvotes: 3
Views: 4700
Reputation: 21241
Yes, PersonViewModel
is a list, and List<T>
does not have a property called personName
.
You want to access properties on an item in the list so:
@Html.DisplayNameFor(m => m.PersonViewModel.personName)
becomes
@Html.DisplayNameFor(m => m.PersonViewModel[0].personName)
(This assumes you will always have at least one item in the list)
I suspect you will have to change the expressions in your loop too...
@Html.DisplayFor(i => i.PersonViewModel.personName)
becomes
@Html.DisplayFor(i => i.personName)
Upvotes: 5