Reputation: 37
I have a table with each record having a ParentId. I need to make a query from my index view to show the name of the Parent record instead of its Id. But I don't know how to use _context from view or how to handle the situation. Currently I can just see the Parent Id as it's in the model itself.
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.CollectionName)
</td>
<td>
@Html.DisplayFor(modelItem => item.ParentId) // I need this to be _context.Groups.FirstOrDefault(m=>m.id == item.ParentId)
</td>
<td>
@Html.DisplayFor(modelItem => item.CollectionHead)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
<a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
}
Upvotes: 1
Views: 822
Reputation: 2674
You shouldn't be passing in a Context
or any database logic to the views.
Your ViewModel should contain all the necessary data you need to display. It looks like in your ViewModel you are passing through a ParentId
but this is really needed in the View. So you could change this to the actual Parent
model or add another field into the ViewModel called ParentName
. Then you'd be able to do something like this in the View, depending which suggestion you go for:
@Html.DisplayFor(modelItem => item.Parent.Name)
or
@Html.DisplayFor(modelItem => item.ParentName)
Without looking at your Controller code it is quite hard to help on how to populate the ViewModel like this. But if your LINQ is correct then you can do this:
viewModel.Parent = _context.Groups.FirstOrDefault(m=>m.id == item.ParentId);
or
viewModel.ParentName = _context.Groups.FirstOrDefault(m=>m.id == item.ParentId).Name;
Upvotes: 3