I have a list of items that I am passing to a view. I would like to render each item using a display template. However, something is wrong, as I don't get the field properly rendered. Here is my main view (Index.cshtml):
@model IEnumerable<CustomEntity>
@{
ViewBag.Title = "Index";
}
@Html.DisplayFor(m=>m)
Here is my display template:
@model CustomEntity
<div>
@Html.LabelFor(m=>m.Name):
<strong>@Model.Name</strong>
@Html.LabelFor(m=>m.Icon):
<strong>@Model.Icon</strong>
@Html.LabelFor(m=>m.TypeName):
<strong>@Model.TypeName</strong>
</div>
The page loads, but doesn't display the values of the entity.
@model IEnumerable<CustomEntity>
@{
ViewBag.Title = "Index";
}
@Html.DisplayForModel()
and then make sure that your display template is stored in ~/Views/Shared/DisplayTemplates/CustomEntity.cshtml
. Notice that the location and the name of the display template is very important. It should be called the same way as the type (CustomEntity.cshtml
) and should be located either in ~/Views/Shared/DisplayTemplates
or you could also override it in ~/Views/XXX/DisplayTemplates
where XXX
is the controller that rendered the main view.
The data you pass in the Html.DisplayFor
of type IEnumerable<CustomEntity>
, but your DisplayTemplate requires a CustomEntity
. Try this instead :
@model IEnumerable<CustomEntity>
@{
ViewBag.Title = "Index";
}
@foreach(var customEntity in Model)
{
@Html.DisplayFor(m => customEntity);
}
来源:https://stackoverflow.com/questions/19568420/mvc-razor-display-template