connectseekers.com

Thursday, 10 August 2017

Ajax Enable Comment System In Asp.Net MVC Using Entity FrameWork

8/10/2017 - By Pranav Singh 0


Now we will create a new asp.net mvc application and add an entity file (.edmx). In this entity file we will add the below entity table.

Now we will add a new controller class file in it. And add the below code in it.

using MVC_Demos.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC_Demos.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        [HttpGet]
        public ActionResult Index()
        {

            return View();
        }

        /// <summary>
        /// Get saved comment
        /// </summary>
        /// <returns></returns>
        public JsonResult CommentDetail()
        {
            CommentModel _commentmodel = new CommentModel();
            DemoEntities _demoEntities = new DemoEntities();
            _commentmodel.CommentList = new List<Comment>();
            var data = _demoEntities.CommentMasters.ToList();
            foreach (var item in data)
            {
                _commentmodel.CommentList.Add(new Comment
                {
                    Name = item.Name,
                    CommentData = item.Comment,
                    CreatedDate = Convert.ToString(item.CreatedDate)
                });
            }
            return Json(_commentmodel.CommentList, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// Save comment
        /// </summary>
        /// <param name="name"></param>
        /// <param name="comment"></param>
        /// <returns></returns>
        public int SaveComment(string name, string comment)
        {
            try
            {
                DemoEntities _demoEntities = new DemoEntities();
                CommentMaster _commentmaster = new CommentMaster();

                _commentmaster.Name = name;
                _commentmaster.Comment = comment;
                _commentmaster.CreatedDate = DateTime.Now ;

                _demoEntities.CommentMasters.Add(_commentmaster);
                _demoEntities.SaveChanges();
                return 1;
            }
            catch
            {
                return 0;
            }
        }
    }
}

 In above code I have written code for saving the posted comment into the database and then then I have created a json function for getting the saved comment for display purpose.

Now we will create a view and add the below jquery reference into the page.


<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>


After this we will add the below jquery code to save the detail and retrieve the detail.

function Postcomment() {
            var username = $("#txtName").val();
            var usercomment = $("#txtComment").val();
            $("#btnValidate").val("Please wait....");
            $.ajax({
                method: "POST",
                url: "/Home/SaveComment/",
                data: { name: username, comment: usercomment }
            })
             .done(function (msg) {
                 if (msg == 1) {
                     $("#divMessage").html("Comment posted successfully.");
                     GetComment();
                 } else {
                     $("#divMessage").html("Error while commenting.");
                 }
                 $("#btnValidate").val("Post Comment");
             });
        }

        //Get all posted comment
        $(document).ready(function () {
            $("#divloadingcomment").html("<b>Please wait loading comments....</b>")
            GetComment();
            $("#divloadingcomment").html("");
        });

        //Function to get detail
        function GetComment() {
            //Call EmpDetails jsonResult Method
            $.getJSON("/Home/CommentDetail/",
            function (json) {
                $('#commenttable tr').remove();
                var tr1;
                var tr2;
                var tr3;
                //Append each row to html table
                for (var i = 0; i < json.length; i++) {
                 
                    tr1 = $('<tr/>');
                    tr1.append("<td><b>" + json[i].Name + "<b></td>");
                    tr1.append("<td><b>(" + json[i].CreatedDate + ")</b></td>");                  
                    $('#commenttable').append(tr1);

                    tr2 = $('<tr/>');
                    tr2.append("<td  colspan='2'>----------------------</td>");
                    $('#commenttable').append(tr2);

                    tr3 = $('<tr/>');
                    tr3.append("<td  colspan='2'>" + json[i].CommentData + "<br/><br/></td>");
                    $('#commenttable').append(tr3);
                }
            });
        }

In above code postcomment() function is used for saving the user comment into the database. And on successful save we have retrieve the saved comment again from the database to display. So for getting the saved comment I have created a function which I have called on view load and other on post of comment.

Here is the complete code of the view page.

@{
    ViewBag.Title = "Ajax Enable Comment System In Asp.Net MVC Using Entity FrameWork ";
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script>
        function Postcomment() {
            var username = $("#txtName").val();
            var usercomment = $("#txtComment").val();
            $("#btnValidate").val("Please wait....");
            $.ajax({
                method: "POST",
                url: "/Home/SaveComment/",
                data: { name: username, comment: usercomment }
            })
             .done(function (msg) {
                 if (msg == 1) {
                     $("#divMessage").html("Comment posted successfully.");
                     GetComment();
                 } else {
                     $("#divMessage").html("Error while commenting.");
                 }
                 $("#btnValidate").val("Post Comment");
             });
        }

        //Get all posted comment
        $(document).ready(function () {
            $("#divloadingcomment").html("<b>Please wait loading comments....</b>")
            GetComment();
            $("#divloadingcomment").html("");
        });

        //Function to get detail
        function GetComment() {
            //Call EmpDetails jsonResult Method
            $.getJSON("/Home/CommentDetail/",
            function (json) {
                $('#commenttable tr').remove();
                var tr1;
                var tr2;
                var tr3;
                //Append each row to html table
                for (var i = 0; i < json.length; i++) {                 
                    tr1 = $('<tr/>');
                    tr1.append("<td><b>" + json[i].Name + "<b></td>");
                    tr1.append("<td><b>(" + json[i].CreatedDate + ")</b></td>");                  
                    $('#commenttable').append(tr1);

                    tr2 = $('<tr/>');
                    tr2.append("<td  colspan='2'>----------------------</td>");
                    $('#commenttable').append(tr2);

                    tr3 = $('<tr/>');
                    tr3.append("<td  colspan='2'>" + json[i].CommentData + "<br/><br/></td>");
                    $('#commenttable').append(tr3);
                }
            });
        }
    </script>
}
@using (Html.BeginForm("Index", "Home"))
{
    <table width="100%" cellpadding="5" cellspacing="2" border="0">
        <tr>
            <td colspan="2">
                <div id="divMessage" style="color:red; font-weight:bold;"></div>
            </td>
        </tr>
        <tr>
            <td>Name : </td>
            <td>@Html.TextBox("name", "", new { @Id = "txtName" })</td>
        </tr>
        <tr>
            <td>Comment : </td>
            <td>@Html.TextArea("comment", "", new { @Id = "txtComment" })</td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:center;">
                <input type="button" value="Post Comment" id="btnValidate" onclick="javascript: Postcomment();" />
            </td>
        </tr>
    </table>
    <div>--------------------Comment--------------------</div>
    <div id="divloadingcomment"></div>
    <table id="commenttable" border="1">
        <tbody></tbody>
    </table>
}

Now we have done run the application to check the output.



Now just have a look of the comment table.




About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com
Email Id : contact@aspdotnet-pools.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Top jQuery Plugins

Global Classified : Connectseekers.com
© 2014 aspdotnet-pools.com Designed by Bloggertheme9.
back to top