ibnhamza
ibnhamza

Reputation: 871

Creating a multi level comments system in asp.net mvc

I'm currently working on a blog written in asp.net mvc. I have a table that stores comments with the following model

public partial class Comment
    {
        public int CommentId { get; set; }
        public string Comment { get; set; }
        public System.DateTime CommentDate { get; set; }
        public int AuthorId { get; set; }
        public int PostId { get; set; }
        public int CategoryId { get; set; }

        public virtual Category Category { get; set; }
        public virtual Post Post { get; set; }
        public virtual UserProfile UserProfile { get; set; }
    } 

Currently the comment is still a one-level comment i.e a user cannot reply to a comment. How can i implement a multilevel comment system in such a way that a comment can have a reply and that reply can have another reply and so on.

Upvotes: 1

Views: 3266

Answers (4)

Miroslav Siska
Miroslav Siska

Reputation: 401

You need create custom Htmlhelper / TreeView and pass data in to this helper. Data model will be according to Mahmoud Moravej.

Upvotes: 0

digiShadoe
digiShadoe

Reputation: 117

But essentially..

I don't know how your POST Class is defined.. Is it a collection? Or a simple class? If it's not a collection you want to make it as so..

Inside your Comment Class Change..

public virtual Post Post { get; set; }

to:

Public virtual ICollection<Post> Posts { get; set; } 

or define it in another class private field..

This will defines the relationship and will be your navigation property as well..

So in your controller you can return both tables like such...

public ActionResult GetComments(int id) { db.context.comments.Include("Posts").Where(c => c.CommentID == id).ToList(); }

Upvotes: 0

Alex Dev
Alex Dev

Reputation: 33

first i need to excuse you for my bad English if you want a tree of comments as i understood like you comment and reply and you need to reply on my reply thats make u should add 1 more field you can call it subcomment id which it will be as an forign key to comment table " self relation " and this subcommenid will hold the parent comment ID

Upvotes: 0

Mahmoud Moravej
Mahmoud Moravej

Reputation: 9034

Add parentCommentId column which refers to the Comments table. After that in each reply :

  1. If it is a direct reply to the post, leave parentCommentId column empty
  2. If it is a reply to a previously posted comment, put that comment id in this column. In this case you can leave postid column empty or not. It depends on your favor!

Upvotes: 6

Related Questions