一个集合中使用用于每个项目DisplayTemplate(带DisplayFor) [英] Using a DisplayTemplate (with DisplayFor) for each item in a collection
问题描述
我已经创建了一个注释
类DisplayTemplate,并将其放置在注释/ 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为注释
类。看来,在它的完整性:
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
行错误:
传递到字典中的模型产品类型'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'.
我怎样才能调用DisplayTemplate在的foreach
循环每一个项目?
How can I invoke the DisplayTemplate for each item in the foreach
loop?
推荐答案
在的IEnumerable&LT;注释&GT;
,并且它是所有遍历收集和简单地调用合适的显示模板:
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)
,其中注释属性是一个的IEnumerable&LT;注释&GT;
这将自动进行循环并呈现 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()
至于其中,
子句中使用的是在那里,你应该简单地将其删除并将此任务委托给控制器。它是控制器的责任prepare视图模式,而不是执行这些任务的看法。
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屋!