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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Won't it search for a DisplayTemplate taking a IEnumerable<CustomEntity> as model, instead of CustomEntity ?
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) ?
@RédaMattar, no, when you pass an IEnumerable<TModel> 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.
@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.
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);
}

1 Comment

There is no need for the foreach loop. MVC handles it by convention so long as everything else is correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.