I'm learning to write MVC websites in C# with ASP.NET and the Entity Framework.
However, I'm struggling to write a dictionary lookup that would work with the Html.DisplayFor
method.
Say I have the following two models:
public class Dog
{
public int Id;
public string Name;
public int BreedId;
(...)
}
public class Breed
{
public int Id;
public string Name;
(...)
}
Then, somewhere in the controller, I'm creating a dictionary containing all the Breeds, indexed by the Id
, and assigning it to ViewBag.Breeds
.
In the Dogs/Index
View, I use something like that:
@model IEnumerable<App.Models.Dog>
<table>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@(ViewBag.Breeds[item.BreedId].Name)
</td>
</tr>
}
</table>
And it generates a table of the Dogs and their Breeds, as intended.
However, if I try to use the dictionary lookup inside the Html.DisplayFor
method, I get an error because an expression tree may not contain a dynamic operation:
@Html.DisplayFor(modelItem => ViewBag.Breeds[item.BreedId].Name)
Casting it to an explicitly typed dictionary doesn't work either:
@Html.DisplayFor(modelItem => ((Dictionary<int, Breed>)ViewBag.Breeds)[item.BreedId].Name)
Is there a way to make it work?