为集合中的每个项目使用 DisplayTemplate(与 DisplayFor) [英] Using a DisplayTemplate (with DisplayFor) for each item in a collection

查看:24
本文介绍了为集合中的每个项目使用 DisplayTemplate(与 DisplayFor)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为 Comment 类创建了一个 DisplayTemplate,并将其放置在 Comment/DisplayTemplates/Comment.cshtml 中.

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

Comment.cshtml 输入正确:

@model Comment

然后,我有一个局部视图,它采用 IEnumerable 作为模型.在那里,我遍历集合并希望将 DisplayTemplate 用于 Comment 类.该视图的完整性:

Then, I have a partial view that takes an IEnumerable<Comment> for model. In there I loop through the collection and would like to use the DisplayTemplate for the Comment class. The view, in its integrity:

@model IEnumerable<Comment>

@foreach (var comment in Model.Where(c => c.Parent == null)) { 
    @Html.DisplayFor(model => comment)
}

但是,我在 Html.DisplayFor 行上收到一个错误:

However, I get an error on the Html.DisplayFor line:

传递给字典的模型项的类型为System.Int32",但此字典需要类型为System.String"的模型项.

The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'System.String'.

如何为 foreach 循环中的每个项目调用 DisplayTemplate?

How can I invoke the DisplayTemplate for each item in the foreach loop?

推荐答案

与其拥有一个采用 IEnumerable 的视图,它所做的只是循环遍历集合并调用适当的简单地显示模板:

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)

其中 Comments 属性是一个 IEnumerable,它将自动执行循环并为该集合的每个项目呈现 Comment.cshtml 显示模板.

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()

就您在其中使用的 Where 子句而言,您应该简单地将其删除并将此任务委托给控制器.准备视图模型是控制器的责任,而不是执行此类任务的视图.

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.

这篇关于为集合中的每个项目使用 DisplayTemplate(与 DisplayFor)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆