Using a DisplayTemplate (with DisplayFor) for each item in a collection

后端 未结 2 1334

I have created a DisplayTemplate for a Comment class, and placed it inside Comment/DisplayTemplates/Comment.cshtml.

Comment.cshtml

2条回答
  •  星月不相逢
    2020-12-05 14:47

    While the accepted answer works well most of the time, there are other cases in which we need to be aware of the element's index when rendering (i.e. add custom javascript that generates references to each element based on their index).

    In that case, DisplayFor can still be used within the loop like this:

    @model IEnumerable
    
    @for (int index = 0; index < Model.Count(); index++)
    {
         @Html.DisplayFor(model => model[index])
    }
    

提交回复
热议问题