MVC Razor display template

一世执手 提交于 2020-01-01 17:26:45

问题


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.


回答1:


@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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!