Search code examples
asp.net-mvcasp.net-mvc-4display-templates

MVC Razor display template


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.


Solution

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