对集合中的每个项目使用 DisplayTemplate(使用 DisplayFor)
我为 Comment
类创建了一个 DisplayTemplate,并将其放置在 Comment/DisplayTemplates/Comment.cshtml
中。
Comment.cshtml
已正确键入:
@model Comment
然后,我有一个采用 IEnumerable
作为模型的部分视图。在那里,我循环访问集合,并希望将 DisplayTemplate 用于 Comment
类。视图的完整性:
@model IEnumerable<Comment>
@foreach (var comment in Model.Where(c => c.Parent == null)) {
@Html.DisplayFor(model => comment)
}
但是,我在 Html.DisplayFor
行上收到错误:
传递到字典中的模型项的类型为“System.Int32”,但该字典需要类型为“System.String”的模型项。
如何为 foreach
循环中的每个项目调用 DisplayTemplate?
I have created a DisplayTemplate for a Comment
class, and placed it inside Comment/DisplayTemplates/Comment.cshtml
.
Comment.cshtml
is properly typed:
@model 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)
}
However, I get an error on the Html.DisplayFor
line:
The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'System.String'.
How can I invoke the DisplayTemplate for each item in the foreach
loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
而不是拥有一个采用
IEnumerable
的视图,它所做的只是循环遍历集合并简单地调用正确的显示模板:其中 Comments 属性是一个
IEnumerable;
它将自动执行循环并为该集合的每个项目呈现Comment.cshtml
显示模板。或者,如果您确实需要这样的视图(不知道为什么),您可以简单地:
就您在其中使用的
Where
子句而言,您应该简单地将其删除并将此任务委托给控制器。准备视图模型是控制器的责任,而不是执行此类任务的视图。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:where the Comments property is an
IEnumerable<Comment>
which will automatically do the looping and render theComment.cshtml
display template for each item of this collection.Or if you really need such a view (don't know why) you could simply:
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.虽然接受的答案在大多数情况下效果很好,但在其他情况下,我们需要在渲染时了解元素的索引(即添加自定义 JavaScript,根据每个元素的索引生成对每个元素的引用)。
在这种情况下,仍然可以在循环中使用 DisplayFor,如下所示:
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: