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

后端 未结 2 1332

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<Comment>
    
    @for (int index = 0; index < Model.Count(); index++)
    {
         @Html.DisplayFor(model => model[index])
    }
    
    0 讨论(0)
  • 2020-12-05 14:58

    Instead of having a view that take an IEnumerable<Comment> and that all it does is loop through the collection and call the proper display template simply:

    @Html.DisplayFor(x => x.Comments)
    

    where the Comments property is an IEnumerable<Comment> which will automatically do the looping and render the Comment.cshtml display template for each item of this collection.

    Or if you really need such a view (don't know why) you could simply:

    @model IEnumerable<Comment>
    @Html.DisplayForModel()
    

    As far as the Where clause you are using in there you should simply remove it and delegate this task to the controller. It's the controller's responsibility to prepare the view model, not the view performing such tasks.

    0 讨论(0)
提交回复
热议问题