Yasser Shaikh
Yasser Shaikh

Reputation: 47784

Displaying nested comments in MVC 3 blog

I am making a Blog using MVC 3, Razor and Entity Framework. I am now working on the Comment section.

I am using the following table for comments.

My Comment table

Here I am using the 'CommentParent' column and setting it a value of an another 'CommentID' if a user is replying to a comment, else I have set a value of null.

Problem

I am using the following code to display comments,

@foreach (var comment in Model.Comments)
{
    <div>
        @comment.CommentContent
    </div>
    <br />
}

I am not sure how to display the "replyTo" comments as shown in the image below... enter image description here Please can anyone guide me as how this can be done...

Upvotes: 2

Views: 3367

Answers (2)

Behnam Esmaili
Behnam Esmaili

Reputation: 5967

try this:

 private void CreateComments(int ? postId, int ? cid)
      {          
        int? id = cid;                
        var replies = new List<Comment>();
        if (postId.HasValue())
        {
              var BlogPost = context.Posts.Single(p=>p.Id == postId.Value);
              replies = BlogPost.Comments.Where(c=>c.CommentParent == null);  
        }
        else
        {
            replies = context.Comments.Where(c=>c.CommentParent == id);         
        }  

        int level = 0;
        Comment tmp = new Comment();
        foreach (Comment reply in replies)
            {     
                tmp = reply;
                while(tmp.CommentParent != null){
                      level++;
                      tmp = context.Comments.Single(c=>c.Id == tmp.CommentParent);
                }
                //logic for creating your html tag 
                //you can use "level" to leave appropriate indent back to your comment.
                CreateComments(null,reply.id);
            }   
     }

Edit:

you can even determine your current level like i did inside foreach loop.

i hope this could help.

Upvotes: 1

Imran Balouch
Imran Balouch

Reputation: 2170

First You will have to change your Model Class, Lets suppose your model class is :

public class CommentsModel
{
     Public Int64 CommentId {get;set;}
     ....
     ....
     //Introduce a new property in it as:
     Public CommentsModel[] ChildComments {get;set;}
}

This new property will hold the child comments of a specific comment up to N Level. Than in your View you can do it like:

@foreach (var comment in Model.Comments)
{
    <div>
    @comment.CommentContent
    </div>
    <br />
    @if(comment.ChildComments.Length > 0)
    {
        // Display Level 1 Comments and so on and so far
    }
}

You can manage the lookout of comments by using Css Class on Divs.

Upvotes: 3

Related Questions