2

我正在使用 MVC 3、Razor 和实体框架制作博客。我现在正在处理评论部分。

我正在使用下表进行评论。

我的评论表

在这里,如果用户正在回复评论,我将使用“CommentParent”列并将其设置为另一个“CommentID”的值,否则我将值设置为 null。

问题

我正在使用以下代码来显示评论,

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

我不确定如何显示“replyTo”评论,如下图所示... 在此处输入图像描述 请任何人指导我如何做到这一点...

4

2 回答 2

2

首先你必须改变你的模型类,假设你的模型类是:

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

这个新属性将把特定评论的子评论保存到 N 级。比在您的视图中您可以这样做:

@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
    }
}

您可以使用 Divs 上的 Css 类来管理评论的查找。

于 2012-07-27T06:09:17.370 回答
1

试试这个:

 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);
            }   
     }

编辑:

你甚至可以像我在 foreach 循环中所做的那样确定你当前的水平。

我希望这会有所帮助。

于 2012-07-27T06:27:36.883 回答