Reputation: 3787
I have Comment model like this:
public class Comment
{
public int? ParentId { get; set; }
public string Text { get; set; }
public int ProjectId { get; set; }
public int UserWhoTypeId { get; set; }
}
I want to show comments one under another by parentID . Parent Comments will seems in div
, child Comments will seems in
<ul>
<li>
child comments go here
</li>
</ul>
For example,
<ul>
<li>
<div>
parent comments go here
</div>
<ul>
<li>
child comments go here
</li>
</ul>
</li>
</ul>
I firstly need to collect Comments with LINQ like tree and then apply it like shown above in view. Any links or advice please.
Edit:
I created model as
public class CommentListModel
{
public Comment Comment{ get; set; }
public List<Comment> Childs { get; set; }
}
And I collected all comments in 1 list:
List<CommentListModel> CommentHierarchy = MyService.GetCommentHierarchy();
Now, I need to show CommentHierarchy in view like tree hierarchy. Please help.
Upvotes: 1
Views: 1324
Reputation: 788
You can change the "Childs" Property of CommentListModel to be a collection of CommentListModel like so:
public class CommentListModel
{
public Comment Comment { get; set; }
public List<CommentListModel> Childs { get; set; }
}
Create a partial view as a display template (put file under DisplayTemplates folder) for CommentListModel:
@model CommentListModel
<ul>
<li>
<div>@Html.DisplayFor(m => m.Comment.Text)</div>
@Html.DisplayFor(m => m.Childs)
</li>
</ul>
Then in your parent view, simply call:
@Html.DisplayFor(m => m)
Assuming the model of the parent view is a collection of CommentListModel objects.
This will allow your list to recurse as deeply as your collection goes.
Upvotes: 2