Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

asp.net mvc - Using a DisplayTemplate (with DisplayFor) for each item in a collection

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...