nn
nnn
n
n
nThe goal of this article is to teach how to structure and display hierarchical data. We will set up a database table structure that can hold data with unlimited parents and children.
nnn
nnn
nnn
nBelow is the completed sample app.
n
n
n
n
nThe Database Table Structure
nLet’s start by planning the table structure. We will be using a single self referenced table for our comment. The structure is shown in the image below.
n
n
n
nAs you can see we have five columns – CommentId which is the primary key, CommentText which holds the comment itself, Username which store the author of the comment, CommentDate and ParentId.
nnn
nnnThe most important column here is the ParentId which is a foreign key to CommentId – This is called self referenced. How this works will be clear as we move on.
n
n
nCreating the Visual Studio Project
nCreate a new ASP.Net MVC web application. Open the index.cshtml file and add the following html codes
nnnnn
nThe next thing is to open the site.css file and replace the code with the following styles
nnn
nIf you run the app now the result should look like this
n
n
n
n
nThe Application Repository
nRight click on the models folder add a new ADO.NET Data Entity Model and the comment table. We need to create methods to fetch and add comments into the comment table.
nnnnnRight click on the models folder and add a class named CommentRepository and replace the code with the following:
n
public class CommentRepositoryn {n CommentEntities context = new CommentEntities();nn public IQueryable GetAll()n {n return context.Comments.OrderBy(x => x.CommentDate);n }nn public commentViewModel AddComment(commentDTO comment)n {n var _comment = new Comment()n {n ParentId = comment.parentId,n CommentText =comment.commentText,n Username = comment.username,n CommentDate =DateTime.Nown };nn context.Comments.Add(_comment);n context.SaveChanges();n return context.Comments.Where(x => x.CommentID == _comment.CommentID)n .Select(x => new commentViewModeln {n commentId = x.CommentID,n commentText =x.CommentText,n parentId =x.ParentId,n commentDate =x.CommentDate,n username =x.Usernamenn }).FirstOrDefault();n }n }nn
nAfter our repository, we also need two methods in the home controller. Modify the HomeController code to reflect this two methods.nn
n
public PartialViewResult CommentPartial()n {n var comments = repo.GetAll();n return PartialView("_CommentPartial", comments);n }nn public JsonResult addNewComment(commentDTO comment)n {n tryn {n var model = repo.AddComment(comment);nn return Json(new { error = false,result=model }, JsonRequestBehavior.AllowGet);nn }n catch (Exception)n {n //Handle Error here..n }nn return Json(new { error = true }, JsonRequestBehavior.AllowGet);n }nnn
nAs you can see, the first method is a PartialViewResult which means that we are returning a partialview. So let’s create the partial view. Add a partial view named _CommentPartial in the shared folder in the root of the solution. Now update the html code in the index.cshtml file by adding the partial view like so:n
n
........nn@Html.Action("CommentPartial")nn
n
nUsing the Razor @Helper syntax to Render Comments
nThe @helper syntax within Razor enables you to easily create re-usable helper methods that can encapsulate output functionality within your view templates. They enable better code reuse, and can also facilitate more readable code. Let’s look at how we will create a recursive comment rendering using this helper.nnOpen up the partial view and add the following code:nn
nn
n
nAdding Comment Javascript and Template
nIf we currently click on the Submit button in the browser we wont get any effect. In order to manipulate comment templates we will require a javascript library called HandleBars. Download and include it in the scripts folder and then add the reference to the index.cshtml file like so:
n
nn
nWe will define two templates, the first one is for the parent comments and the second will be for the replies. The comment template look like this:nn
nn
nnAnd the reply template:nn
n
nWe will be using ajax to submit and retrieve comments so lets write the ajax method. In the script section of the index.cshtl file create a javascript function called addNewComment like so:nn
n
function addNewComment(data) {n return $.ajax({n type: "POST",n url: '@Url.Action("addNewComment", "Home")',n data: data,n dataType: 'json',n contentType: 'application/json;charset=utf-8'n });n }n
nThe complete javascript code that is responsible for adding comments and replies look like so:nn
n
nThat is it! I have included the link for the complete source code in my github page.nnYour comments and suggestions are welcome.

