Introduction

A comments system has become very important in order to share our opinion on social media and forums with others.

So, in this article, we will implement comments system by using ASP.NET MVC 5 and jQuery, Bootstrap. I hope you will like this.

Prerequisites

Make sure you have installed Visual Studio 2015 (.NET Framework 4.5.2) and SQL Server.

In this post, we are going to:

  • Create database.
  • Create MVC application.
  • Configuring entity framework ORM to connect to the database.
  • Create our Comments Controller.
  • Create Razor pages in order to build our application.

SQL Database part

Here, you find the scripts to create database and tables.

Create Database

  1. USE [master]
  2. GO
  3. /****** Object: Database [DBComments] Script Date: 11/20/2017 2:23:19 PM ******/
  4. CREATE DATABASE [DBComments]
  5. CONTAINMENT = NONE
  6. ON PRIMARY
  7. ( NAME = N'DBComments', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DBComments.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
  8. LOG ON
  9. ( NAME = N'DBComments_log', FILENAME = N'c:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\DBComments_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
  10. GO
  11. ALTER DATABASE [DBComments] SET COMPATIBILITY_LEVEL = 110
  12. GO
  13. IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
  14. begin
  15. EXEC [DBComments].[dbo].[sp_fulltext_database] @action = 'enable'
  16. end
  17. GO
  18. ALTER DATABASE [DBComments] SET ANSI_NULL_DEFAULT OFF
  19. GO
  20. ALTER DATABASE [DBComments] SET ANSI_NULLS OFF
  21. GO
  22. ALTER DATABASE [DBComments] SET ANSI_PADDING OFF
  23. GO
  24. ALTER DATABASE [DBComments] SET ANSI_WARNINGS OFF
  25. GO
  26. ALTER DATABASE [DBComments] SET ARITHABORT OFF
  27. GO
  28. ALTER DATABASE [DBComments] SET AUTO_CLOSE OFF
  29. GO
  30. ALTER DATABASE [DBComments] SET AUTO_CREATE_STATISTICS ON
  31. GO
  32. ALTER DATABASE [DBComments] SET AUTO_SHRINK OFF
  33. GO
  34. ALTER DATABASE [DBComments] SET AUTO_UPDATE_STATISTICS ON
  35. GO
  36. ALTER DATABASE [DBComments] SET CURSOR_CLOSE_ON_COMMIT OFF
  37. GO
  38. ALTER DATABASE [DBComments] SET CURSOR_DEFAULT GLOBAL
  39. GO
  40. ALTER DATABASE [DBComments] SET CONCAT_NULL_YIELDS_NULL OFF
  41. GO
  42. ALTER DATABASE [DBComments] SET NUMERIC_ROUNDABORT OFF
  43. GO
  44. ALTER DATABASE [DBComments] SET QUOTED_IDENTIFIER OFF
  45. GO
  46. ALTER DATABASE [DBComments] SET RECURSIVE_TRIGGERS OFF
  47. GO
  48. ALTER DATABASE [DBComments] SET DISABLE_BROKER
  49. GO
  50. ALTER DATABASE [DBComments] SET AUTO_UPDATE_STATISTICS_ASYNC OFF
  51. GO
  52. ALTER DATABASE [DBComments] SET DATE_CORRELATION_OPTIMIZATION OFF
  53. GO
  54. ALTER DATABASE [DBComments] SET TRUSTWORTHY OFF
  55. GO
  56. ALTER DATABASE [DBComments] SET ALLOW_SNAPSHOT_ISOLATION OFF
  57. GO
  58. ALTER DATABASE [DBComments] SET PARAMETERIZATION SIMPLE
  59. GO
  60. ALTER DATABASE [DBComments] SET READ_COMMITTED_SNAPSHOT OFF
  61. GO
  62. ALTER DATABASE [DBComments] SET HONOR_BROKER_PRIORITY OFF
  63. GO
  64. ALTER DATABASE [DBComments] SET RECOVERY SIMPLE
  65. GO
  66. ALTER DATABASE [DBComments] SET MULTI_USER
  67. GO
  68. ALTER DATABASE [DBComments] SET PAGE_VERIFY CHECKSUM
  69. GO
  70. ALTER DATABASE [DBComments] SET DB_CHAINING OFF
  71. GO
  72. ALTER DATABASE [DBComments] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )
  73. GO
  74. ALTER DATABASE [DBComments] SET TARGET_RECOVERY_TIME = 0 SECONDS
  75. GO
  76. ALTER DATABASE [DBComments] SET READ_WRITE
  77. GO

Create Tables

After creating a database, we will move to create all the needed tables.

Users Table

  1. USE [DBComments]
  2. GO
  3. /****** Object: Table [dbo].[Users] Script Date: 11/20/2017 2:24:16 PM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. SET ANSI_PADDING ON
  9. GO
  10. CREATE TABLE [dbo].[Users](
  11. [UserID] [int] IDENTITY(1,1) NOT NULL,
  12. [Username] [varchar](50) NULL,
  13. [imageProfile] [varchar](50) NULL,
  14. CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
  15. (
  16. [UserID] ASC
  17. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  18. ) ON [PRIMARY]
  19. GO
  20. SET ANSI_PADDING OFF
  21. GO

Posts Table

  1. USE [DBComments]
  2. GO
  3. /****** Object: Table [dbo].[Posts] Script Date: 11/20/2017 2:24:42 PM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. SET ANSI_PADDING ON
  9. GO
  10. CREATE TABLE [dbo].[Posts](
  11. [PostID] [int] IDENTITY(1,1) NOT NULL,
  12. [Message] [varchar](50) NULL,
  13. [PostedDate] [datetime] NULL,
  14. CONSTRAINT [PK_Posts] PRIMARY KEY CLUSTERED
  15. (
  16. [PostID] ASC
  17. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  18. ) ON [PRIMARY]
  19. GO
  20. SET ANSI_PADDING OFF
  21. GO

Comments Table

  1. USE [DBComments]
  2. GO
  3. /****** Object: Table [dbo].[Comments] Script Date: 11/20/2017 2:25:03 PM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. SET ANSI_PADDING ON
  9. GO
  10. CREATE TABLE [dbo].[Comments](
  11. [ComID] [int] IDENTITY(1,1) NOT NULL,
  12. [CommentMsg] [varchar](max) NULL,
  13. [CommentedDate] [datetime] NULL,
  14. [PostID] [int] NULL,
  15. [UserID] [int] NULL,
  16. CONSTRAINT [PK_Comments] PRIMARY KEY CLUSTERED
  17. (
  18. [ComID] ASC
  19. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  20. ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  21. GO
  22. SET ANSI_PADDING OFF
  23. GO
  24. ALTER TABLE [dbo].[Comments] WITH CHECK ADD CONSTRAINT [FK_Comments_Users] FOREIGN KEY([PostID])
  25. REFERENCES [dbo].[Posts] ([PostID])
  26. GO
  27. ALTER TABLE [dbo].[Comments] CHECK CONSTRAINT [FK_Comments_Users]
  28. GO
  29. ALTER TABLE [dbo].[Comments] WITH CHECK ADD CONSTRAINT [FK_Comments_Users1] FOREIGN KEY([UserID])
  30. REFERENCES [dbo].[Users] ([UserID])
  31. GO
  32. ALTER TABLE [dbo].[Comments] CHECK CONSTRAINT [FK_Comments_Users1]
  33. GO

SubComments Table

  1. USE [DBComments]
  2. GO
  3. /****** Object: Table [dbo].[SubComments] Script Date: 11/20/2017 2:25:29 PM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. SET ANSI_PADDING ON
  9. GO
  10. CREATE TABLE [dbo].[SubComments](
  11. [SubComID] [int] IDENTITY(1,1) NOT NULL,
  12. [CommentMsg] [varchar](50) NULL,
  13. [CommentedDate] [datetime] NULL,
  14. [ComID] [int] NULL,
  15. [UserID] [int] NULL,
  16. CONSTRAINT [PK_SubComments] PRIMARY KEY CLUSTERED
  17. (
  18. [SubComID] ASC
  19. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  20. ) ON [PRIMARY]
  21. GO
  22. SET ANSI_PADDING OFF
  23. GO
  24. ALTER TABLE [dbo].[SubComments] WITH CHECK ADD CONSTRAINT [FK_SubComments_Comments] FOREIGN KEY([ComID])
  25. REFERENCES [dbo].[Comments] ([ComID])
  26. GO
  27. ALTER TABLE [dbo].[SubComments] CHECK CONSTRAINT [FK_SubComments_Comments]
  28. GO
  29. ALTER TABLE [dbo].[SubComments] WITH CHECK ADD CONSTRAINT [FK_SubComments_Users] FOREIGN KEY([UserID])
  30. REFERENCES [dbo].[Users] ([UserID])
  31. GO
  32. ALTER TABLE [dbo].[SubComments] CHECK CONSTRAINT [FK_SubComments_Users]
  33. GO
Create your MVC application

Open Visual Studio and select File >> New Project.

The "New Project" window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.

Next, a new dialog will pop up for selecting the template. We are going to choose MVC template and click OK.

Once our project is created, we will add ADO.NET Entity Data Model.

Adding ADO.NET Entity Data Model

Right-click on the project name, click Add >> Add New Item.

A dialog box will pop up. Inside Visual C#, select Data >> ADO.NET Entity Data Model, and enter the name for your DbContext model as SysComments, then click Add.

As you can see, we have 4 model contents. We are selecting the first approach (EF Designer from database).
As you can see below, we need to select server name, then via drop-down list connected to a database section, you must choose your database name and finally click OK.
For the next step, the dialog Entity Data Model Wizard will pop up for choosing objects which will be used in our application. We are selecting all the tables except sysdiagrams and click Finish.
Finally, we can see that EDMX model generates all objects, as shown below.

Create a Controller

Now, we are going to create a Controller. Right-click on the Controllers folder> > Add >> Controller>> selecting MVC 5 Controller - Empty>> click Add. In the next dialog, name the controller CommentsController and then click Add.

CommentsController.cs

Here, we have used Get Users action in order to authenticate user by providing her/his username. If the user exists in users table, we will redirect him to Get Posts action, otherwise the following message ‘username does not exist’ will be displayed.

  1. [HttpGet]
  2. public ActionResult GetUsers()
  3. {
  4. return View();
  5. }
  6. [HttpPost]
  7. public ActionResult GetUsers(string username)
  8. {
  9. User user = dbContext.Users.Where(u => u.Username.ToLower() == username.ToLower())
  10. .FirstOrDefault();
  11. if(user != null)
  12. {
  13. Session["UserID"] = user.UserID;
  14. return RedirectToAction("GetPosts");
  15. }
  16. ViewBag.Msg = "Username does not exist !";
  17. return View();
  18. }

GetUsers.cshtml

  1. @{
  2. ViewBag.Title = "GetUsers";
  3. }
  4. @using (Html.BeginForm("GetUsers", "Comments", FormMethod.Post))
  5. {
  6. <div class="blockUser" style="width: 44%; margin: 16% 26%;">
  7. <div style="margin-left: 23%;">
  8. <input type="text" class="form-control input-lg" name="username" placeholder="Username" /><br />
  9. <input type="submit" class="btn btn-success btn-lg" value="Let's GO ^_^" style="width: 75%;" />
  10. </div>
  11. </div>
  12. }
  13. @if (ViewBag.Msg != null)
  14. {
  15. <div class="alert alert-danger" role="alert">Oups! @ViewBag.Msg</div>
  16. }

In order to display all posts, we have created Get Posts action which selects all posts from posts table, then displayed them within GetPosts.cshtml by using foreach loop.

  1. [HttpGet]
  2. public ActionResult GetPosts()
  3. {
  4. IQueryable<PostsVM> Posts = dbContext.Posts
  5. .Select(p => new PostsVM
  6. {
  7. PostID = p.PostID,
  8. Message = p.Message,
  9. PostedDate = p.PostedDate.Value
  10. }).AsQueryable();
  11. return View(Posts);
  12. }

GetPosts.cshtml

  1. @model IQueryable<CommentsSystemMVC5.ViewModels.PostsVM>
  2. @{
  3. ViewBag.Title = "GetPosts";
  4. }
  5. @if (Model != null)
  6. {
  7. foreach (var post in Model)
  8. {
  9. <div class="panel panel-default" style="width: 80%;">
  10. <div class="panel-body">
  11. <div class="avatar">
  12. <img src="~/Images/avatar.png" class="img-circle" style="width: 60px;"/>
  13. <span> <a href="" style="font-weight:bold">Leo Messi</a> </span><br />
  14. <p style="margin-left: 60px; margin-top: -19px;">
  15. <span class="glyphicon glyphicon-time" aria-hidden="true"></span>
  16. <time class="timeago" datetime="@post.PostedDate">@post.PostedDate</time>
  17. </p>
  18. </div>
  19. <div class="postMessage" style="margin-top: 11px; margin-left: 9px;">
  20. <span class="label label-warning"> @string.Format("Post #{0}", post.PostID) </span><br />
  21. <p class="message">
  22. @post.Message
  23. </p>
  24. </div>
  25. </div>
  26. <div class="panel-footer">
  27. <button type="button" class="btn btn-default Comment" data-id="@post.PostID" value="Comment">
  28. <span class="glyphicon glyphicon-comment" aria-hidden="true"></span> Comment
  29. </button>
  30. </div>
  31. <div id="@string.Format("{0}_{1}","commentsBlock", post.PostID)" style="border: 1px solid #f1eaea; background-color: #eaf2ff;">
  32. <div class="AddComment" style="margin-left: 30%; margin-bottom: 5px; margin-top: 8px;">
  33. <input type="text" id="@string.Format("{0}_{1}", "comment", post.PostID)" class="form-control" placeholder="Add a Comment ..." style="display: inline;" />
  34. <button type="button" class="btn btn-default addComment" data-id="@post.PostID"><span class="glyphicon glyphicon-comment" aria-hidden="true"></span></button>
  35. </div>
  36. </div>
  37. </div>
  38. }
  39. }
  40. @section Scripts
  41. {
  42. <script type="text/javascript">
  43. $(document).ready(function () {
  44. //Click Comment
  45. $('.Comment').on('click', function () {
  46. var id = $(this).attr("data-id");
  47. var allCommentsArea = $('<div>').addClass('allComments_' + id);
  48. //function that allow us to get all comments related to post id
  49. $.ajax({
  50. type: 'GET',
  51. url: '@Url.Action("GetComments", "Comments")',
  52. data: { postId: id },
  53. success: function (response) {
  54. if ($('div').hasClass('allComments_' + id + ''))
  55. {
  56. $('div[class=allComments_' + id + ']').remove();
  57. }
  58. //console.log(response);
  59. allCommentsArea.html(response);
  60. allCommentsArea.prependTo('#commentsBlock_' + id);
  61. },
  62. error: function (response) {
  63. alert('Sorry: Comments cannot be loaded !');
  64. }
  65. })
  66. });
  67. //Add New Comment
  68. $('.addComment').on('click', function () {
  69. var postId = $(this).attr('data-id');
  70. var commentMsg = $('#comment_' + postId).val();
  71. var dateTimeNow = new Date();
  72. //alert('Hello');
  73. var comment = {
  74. CommentMsg: commentMsg,
  75. CommentedDate: dateTimeNow.toLocaleString()
  76. };
  77. $.ajax({
  78. type: 'POST',
  79. url: '@Url.Action("AddComment", "Comments")',
  80. data: { comment, postId },
  81. success: function (response) {
  82. $('div[class=allComments_' + postId + ']').remove();
  83. var allCommentsArea = $('<div>').addClass('allComments_' + postId);
  84. allCommentsArea.html(response);
  85. allCommentsArea.prependTo('#commentsBlock_' + postId);
  86. },
  87. error: function (response) {
  88. alert('Sorry: Something Wrong');
  89. }
  90. });
  91. });
  92. jQuery("time.timeago").timeago();
  93. });
  94. </script>
  95. }

As you can see, Get Comments action is responsible to get all comments related to the given post id, then we will display them within _MyComments partial view.

  1. public PartialViewResult GetComments(int postId)
  2. {
  3. IQueryable<CommentsVM> comments = dbContext.Comments.Where(c => c.Post.PostID == postId)
  4. .Select(c => new CommentsVM
  5. {
  6. ComID = c.ComID,
  7. CommentedDate = c.CommentedDate.Value,
  8. CommentMsg = c.CommentMsg,
  9. Users = new UserVM
  10. {
  11. UserID = c.User.UserID,
  12. Username = c.User.Username,
  13. imageProfile = c.User.imageProfile
  14. }
  15. }).AsQueryable();
  16. return PartialView("~/Views/Shared/_MyComments.cshtml", comments);
  17. }

Shared/_MyComments.cshtml

To add partial view, from the Solution Explorer, expand Views folder, right click on Shared folder >> Add >> View. Don’t forget to check "Create as a partial view" option.

  1. @model IQueryable<CommentsSystemMVC5.ViewModels.CommentsVM>
  2. @using CommentsSystemMVC5.ViewModels;
  3. @if (Model != null)
  4. {
  5. foreach (CommentsVM comment in Model)
  6. {
  7. <div class="row" style="width: 100.3%; border-bottom: 1px solid #d2cece; margin-right: -14px; margin-left: -1px;">
  8. <div class="col-md-4" style="width: 21%;">
  9. <div class="userProfil" style="margin-left: 9px; margin-top: 12px;">
  10. <img src="~/Images/@comment.Users.imageProfile" class="img-circle" style="width: 46px; height: 53px; border: 1px solid #bcb8b8;" />
  11. <a href="#" style="margin-left: 5px; font-weight: bold; font-size: 13px;"> @comment.Users.Username </a>
  12. </div>
  13. </div>
  14. <div class="col-md-7" style="width: 60%;">
  15. <div class="commentDetails">
  16. <p style="margin-top: 27px; font-size: 13px; color: #9c9898;"> @comment.CommentMsg </p>
  17. <a href="#" class="Reply" data-id="@comment.ComID">Reply</a>
  18. <div class="@string.Format("{0}_{1}", "ReplayComments", comment.ComID)" style="display:none;">
  19. <div class="ReplayCommentInput" style="margin-left: 3%; margin-bottom: 5px; margin-top: 8px;">
  20. <input type="text" id="@string.Format("{0}_{1}", "inputReplay", comment.ComID)" class="form-control" placeholder="Add a Comment ..." style="display: inline;" />
  21. <button type="button" class="btn btn-default ReplyAddComment" data-id="@comment.ComID"><span class="glyphicon glyphicon-comment" aria-hidden="true"></span></button>
  22. </div>
  23. </div>
  24. </div>
  25. </div>
  26. <div class="col-md-1" style="width: 19%;">
  27. <div class="commentDate">
  28. <span class="glyphicon glyphicon-time" aria-hidden="true"></span>
  29. <time class="timeago" style="margin-top: 27px; font-size: 13px; color: #9c9898; margin-left: 4px;" datetime="@comment.CommentedDate">@comment.CommentedDate</time>
  30. </div>
  31. </div>
  32. </div>
  33. }
  34. }
  35. <script type="text/javascript">
  36. $(document).ready(function () {
  37. //Get All ReplyComment
  38. $('.Reply').on('click', function () {
  39. var ComID = $(this).attr('data-id');
  40. $.ajax({
  41. type: 'GET',
  42. url: '@Url.Action("GetSubComments", "Comments")',
  43. data: { ComID },
  44. success: function (response) {
  45. if ($('div').hasClass('zoneReply_' + ComID + ''))
  46. {
  47. $('div [class=zoneReply_' + ComID + ']').remove();
  48. }
  49. var selReply = $("<div>").addClass('zoneReply_' + ComID);
  50. selReply.append(response);
  51. selReply.prependTo($('.ReplayComments_' + ComID));
  52. $('.ReplayComments_' + ComID).show();
  53. },
  54. error: function (response) {
  55. alert('something Wrong');
  56. }
  57. });
  58. });
  59. //Add Reply Comment
  60. $('.ReplyAddComment').on('click', function () {
  61. var ComID = $(this).attr('data-id');
  62. var CommentMsg = $('#inputReplay_' + ComID).val();
  63. var dateTimeNow = new Date();
  64. var subComment = {
  65. CommentMsg: CommentMsg,
  66. CommentedDate: dateTimeNow.toLocaleString()
  67. };
  68. $.ajax({
  69. type: 'POST',
  70. url: '@Url.Action("AddSubComment", "Comments")',
  71. data: { subComment, ComID },
  72. success: function (response) {
  73. if ($('div').hasClass('zoneReply_' + ComID + '')) {
  74. $('div [class=zoneReply_' + ComID + ']').remove();
  75. }
  76. var selReply = $("<div>").addClass('zoneReply_' + ComID);
  77. selReply.append(response);
  78. selReply.prependTo($('.ReplayComments_' + ComID));
  79. $('.ReplayComments_' + ComID).show();
  80. },
  81. error: function (response) {
  82. alert('something Wrong');
  83. }
  84. });
  85. });
  86. jQuery("time.timeago").timeago();
  87. })
  88. </script>

Adding a comment is very simple. We have created Add Comment action which accepts the comment and posts id parameters then persisting comment object into comments table by using add extension method.

  1. [HttpPost]
  2. public ActionResult AddComment(CommentsVM comment, int postId)
  3. {
  4. //bool result = false;
  5. Comment commentEntity = null;
  6. int userId = (int)Session["UserID"];
  7. var user = dbContext.Users.FirstOrDefault(u => u.UserID == userId);
  8. var post = dbContext.Posts.FirstOrDefault(p => p.PostID == postId);
  9. if (comment != null)
  10. {
  11. commentEntity = new EDMX.Comment
  12. {
  13. CommentMsg = comment.CommentMsg,
  14. CommentedDate = comment.CommentedDate,
  15. };
  16. if (user != null && post != null)
  17. {
  18. post.Comments.Add(commentEntity);
  19. user.Comments.Add(commentEntity);
  20. dbContext.SaveChanges();
  21. //result = true;
  22. }
  23. }
  24. return RedirectToAction("GetComments", "Comments", new { postId = postId });
  25. }

Here, Get subComments is used to select all sub comments related to the given comID (comment id). Then, we will display them within _MySubComments partial view.

  1. [HttpGet]
  2. public PartialViewResult GetSubComments(int ComID)
  3. {
  4. IQueryable<SubCommentsVM> subComments = dbContext.SubComments.Where(sc => sc.Comment.ComID == ComID)
  5. .Select(sc => new SubCommentsVM
  6. {
  7. SubComID = sc.SubComID,
  8. CommentMsg = sc.CommentMsg,
  9. CommentedDate = sc.CommentedDate.Value,
  10. User = new UserVM
  11. {
  12. UserID = sc.User.UserID,
  13. Username = sc.User.Username,
  14. imageProfile = sc.User.imageProfile
  15. }
  16. }).AsQueryable();
  17. return PartialView("~/Views/Shared/_MySubComments.cshtml", subComments);

  18. }

Shared/_MySubComments.cshtml

  1. @model IQueryable<CommentsSystemMVC5.ViewModels.SubCommentsVM>
  2. @using CommentsSystemMVC5.ViewModels
  3. @if (Model != null)
  4. {
  5. foreach (SubCommentsVM subComment in Model)
  6. {
  7. <div class="row" style="width: 100.3%; border-bottom: 1px solid #d2cece; margin-right: -14px; margin-left: -1px;">
  8. <div class="col-md-4" style="width: 36%;">
  9. <div class="userProfil" style="margin-left: 9px; margin-top: 12px;">
  10. <img src="~/Images/@subComment.User.imageProfile" class="img-circle" style="width: 46px; height: 53px; border: 1px solid #bcb8b8;" />
  11. <a href="#" style="margin-left: 5px; font-weight: bold; font-size: 13px;"> @subComment.User.Username </a>
  12. </div>
  13. </div>
  14. <div class="col-md-7" style="width: 32%;">
  15. <div class="commentDetails">
  16. <p style="margin-top: 27px; font-size: 13px; color: #9c9898;"> @subComment.CommentMsg </p>
  17. </div>
  18. </div>
  19. <div class="col-md-1" style="width: 32%;">
  20. <div class="commentDetails">
  21. <span class="glyphicon glyphicon-time" aria-hidden="true"></span>
  22. <time class="timeago" style="margin-top: 27px; font-size: 13px; color: #9c9898; margin-left: 4px;" datetime="@subComment.CommentedDate">@subComment.CommentedDate</time>
  23. </div>
  24. </div>
  25. </div>
  26. }
  27. }
  28. <script type="text/javascript">
  29. $(document).ready(function () {
  30. jQuery("time.timeago").timeago();
  31. });
  32. </script>
  1. [HttpPost]
  2. public ActionResult AddSubComment(SubCommentsVM subComment, int ComID)
  3. {
  4. SubComment subCommentEntity = null;
  5. int userId = (int)Session["UserID"];
  6. var user = dbContext.Users.FirstOrDefault(u => u.UserID == userId);
  7. var comment = dbContext.Comments.FirstOrDefault(p => p.ComID == ComID);
  8. if (subComment != null)
  9. {
  10. subCommentEntity = new EDMX.SubComment
  11. {
  12. CommentMsg = subComment.CommentMsg,
  13. CommentedDate = subComment.CommentedDate,
  14. };
  15. if (user != null && comment != null)
  16. {
  17. comment.SubComments.Add(subCommentEntity);
  18. user.SubComments.Add(subCommentEntity);
  19. dbContext.SaveChanges();
  20. //result = true;
  21. }
  22. }
  23. return RedirectToAction("GetSubComments", "Comments", new { ComID = ComID });
  24. }

View Model

Don’t forget to add the the following View Models.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. namespace CommentsSystemMVC5.ViewModels
  6. {
  7. public class PostsVM
  8. {
  9. public int PostID { get; set; }
  10. public string Message { get; set; }
  11. public DateTime PostedDate { get; set; }
  12. }
  13. public class CommentsVM
  14. {
  15. public int ComID { get; set; }
  16. public string CommentMsg { get; set; }
  17. public DateTime CommentedDate { get; set; }
  18. public PostsVM Posts { get; set; }
  19. public UserVM Users { get; set; }
  20. }
  21. public class UserVM
  22. {
  23. public int UserID { get; set; }
  24. public string Username { get; set; }
  25. public string imageProfile { get; set; }
  26. }
  27. public class SubCommentsVM
  28. {
  29. public int SubComID { get; set; }
  30. public string CommentMsg { get; set; }
  31. public DateTime CommentedDate { get; set; }
  32. public CommentsVM Comment { get; set; }
  33. public UserVM User { get; set; }
  34. }
  35. }

Output

Now, our comments system application is ready. We can run and see the output in the browser.



That’s all. Please send your feedback and queries in comments box.