3

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
laconicdev
  • 6,360
  • 11
  • 63
  • 89

2 Answers2

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

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Won't it search for a DisplayTemplate taking a `IEnumerable` as model, instead of `CustomEntity` ? – Réda Mattar Oct 24 '13 at 14:43
  • Thank you Darin! I was missing the proper name for my display template. It was called Entity instead of CustomEntity. Once I changed the name, it's working. Can you tell me the difference between @Html.DisplayForModel() and @Html.DisplayFor(m=>m) ? – laconicdev Oct 24 '13 at 15:06
  • @RédaMattar, no, when you pass an `IEnumerable` as a property to a display or editor template it will look for a template named `TModel.cshtml` and it will automatically invoke it for each element of this collection so that you don't need to be writing any `foreach` loops in your code. It all works by convention. – Darin Dimitrov Oct 25 '13 at 05:59
  • 1
    @laconicdev, there's no difference between `@Html.DisplayForModel()` and `@Html.DisplayFor(m => m)`. It's just that `@Html.DisplayForModel()` seems more natural in this case. – Darin Dimitrov Oct 25 '13 at 06:00
0

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);
}
Réda Mattar
  • 4,361
  • 1
  • 18
  • 19
  • 1
    There is no need for the foreach loop. MVC handles it by convention so long as everything else is correct. – Carl Aug 04 '14 at 23:20