CRUD Operations Using jQuery AJAX in ASP.NET MVC

   10/6/2021 6:30:41 AM     CRUD Operation ASP.NET MVC jQuery AJAX Entityframwork     2

Share us on:

Linkedin GooglePlus

In this article, I am going to explain and implement CRUD (Insert, Update, Delete, Read) operations step by step using Jquery ajax in ASP.NET MVC application.

CRUD Operation using jquery in MVC without refresh(refreshing) page. this is important features of any application.

I have used simple MVC Structure,there are three layer Model, View, Controller.

Model: I have created Employee Model, there are some properties of employee like empName,empCountry

Controller: In Controller there are 5 ActionResult method for Inseret, Update, Delete and Read Operation. I have used Technology C#, EntityFramwork. i have implemented logic With the help of C# and created connectivity with database using EntityFramwork.With help of these technology i can modify data in database table and return data on View.

View: In View, there are HTML Code And jQuery Script. I have built HTML Table Grid With help of tr and td tag and jQuery AJAX functions for implementing CRUD Operation.


Now , I am going to explain and implement CRUD (Insert, Update, Delete, Read) operations using Asp.Net MVC with help of jquery ajax.

Database table design structure


 CREATE TABLE [dbo].[tblEmp]
   (
       [empId] [int] IDENTITY(1,1) NOT NULL,
       [empName] [varchar](50) NULL,
       [empCountry] [varchar](50) NULL
   )

Open Visual Studio and click on Create a New Application

Open-VisualStudio

 

Select Asp.Net Web Application and click on next

AspNetMvc-Application

 

Select MVC For Asp.net MVC Solution

MVC-App

 

Configure Settings for Solution

Configure-solution

 

Here, i am going to explain coding and design structure of CURD Operation

Controller

        In Controller there are 5 method for CURD (Insert, Update, Delete, Select) Operation, its used to we can perform insert update delete  and read with help of C# and Entityframwork

 


public ActionResult Index()
        {
            return View();
        }
        public JsonResult EmpList()
        {
            return Json(_context.emp.ToList(), JsonRequestBehavior.AllowGet);
        }
        public JsonResult  AddNewEmp(Employee obj)
        {
            string status = string.Empty;
            try
            {
                _context.emp.Add(obj);
                _context.SaveChanges();
                status = "Record inserted successfully.";
            }

            catch (Exception ex)
            {
                status = "!!!there are some problem.";
            }
            return Json(status, JsonRequestBehavior.AllowGet);
        }
        
        [HttpPost]
        public  ActionResult UpdateEmp(Employee obj)
        {
            string status = string.Empty;
            try
            {
                Employee e = _context.emp.FirstOrDefault(a => a.empId == obj.empId);
                e .empName = obj.empName;
                e .empCountry = obj.empCountry;
                _context.SaveChanges();
                status = "record updated successfully.";
            }
            catch (Exception ex)
            {
                status = "!!!There are some problem.";
            }
            return Json(status, JsonRequestBehavior.AllowGet);
        }
        public  ActionResult DeleteEmp(int empId)
        {
            string status = string.Empty;
            try
            {
                Employee e = _context.emp.FirstOrDefault(a => a.empId == empId);
                _context.emp.Remove(e);
                _context.SaveChanges();
                status = "record deleted successfully.";
            }
            catch (Exception ex)
            {
                status = "!!!There are some problem.";
            }
            return Json(status, JsonRequestBehavior.AllowGet);
        }


 

Model

           I have created Employee model with properties for CRUD Operation 

 


    [Table("tblEmp")]
    public class Employee
    {
        [Key]
        public int empId { get; set; }
        public string empName { get; set; }
        public string empCountry { get; set; }
    }

View

          I have created view Index , Which contain Html table Grid where i will implement and perform CRUD(Insert, Update, Delete, Read) Operations. it is created by tr and td tag. 

 

With help of jQuery i will implement and perform CRUD Operation.



<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <table id="tblEmployee" class="table" cellpadding="0" cellspacing="0">
        <thead>
            <tr>
                <th style="width: 100px; background-color: lightseagreen;">Emp Id</th>
                <th style="width:150px;background-color: lightseagreen";>EmpName</th>
                <th style="width:150px;background-color: lightseagreen";>EmpCountry</th>
                <th style="width:115px;"><input type="button" class="btn btn-danger" id="btnAdd" onclick="AddNew();" value="Add New" /></th>
            </tr>
        </thead>
        <tbody class="tbody">
        </tbody>
    </table>

    <script type="text/javascript">

        //Refresh Data
        $(document).ready(function () {
            GetfreshData();
        });

        //load function
           function GetfreshData() {
            $.ajax({
                url: "/Home/EmpList",
                type: "GET",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (result) {
                    var htmlRow = '';
                    $.each(result, function (key, item) {
                         htmlRow += '<tr>';
                        htmlRow += '<td class="empId" style="width: 100px;"><span>' +
                                   item.empId + '</span> <input type="text" value="' + item.empId
                                   + '" style="display:none" /></td>';
                        htmlRow += '<td class="empName" style="width: 150px;"><span>' +
                                   item.empName + '</span> <input type="text" value="' + 
                                   item.empName + '" style="display:none" /></td>';
                        htmlRow += '<td class="empCountry" style="width: 150px;">
                                   <span>' + item.empCountry + '</span> <input type="text"
                                   value="' + item.empCountry + '" style="display:none" /></td>';
                        htmlRow += '<td style="width: 100px;"><a href="#" class="edit"
                                   >Edit</a> | <a href="#" class="delete" onclick="Delele(' +
                                   item.empId + ')">Delete</a><a class="btn btn-primary update"
                                   href="javascript:;" style="display:none">Update</a>| <a
                                   class="btn btn-danger cancel" href="javascript:;"
                                   onclick="Cancel();" style="display:none">Cancel</a></td>';
                        htmlRow += '</tr>';
                    });
                    $('.tbody').html(htmlRow);
                },
                error: function (errormsg) {
                    alert(errormsg.responseText);
                }
            });
        }


        //Add Data Function
        function AddNew() {
            $('#tblEmployee .tbody').append('<tr><td class="empId" style="width:
                               100px;"><input type="text" value="" style="" /></td><td class="empName"
                               style="width: 150px;"><input type="text" value="" style="" /></td><td
                               class="empCountry" style="width: 150px;"><input type="text" value=""
                               style="" /></td><td style="width: 100px;"><a href="#" class="addNew">Add</a>
                             | <a href="#" onclick="DeleleNewRow(event)">Delete</a></td></tr>');
        }
        //Delete cell
        function DeleleNewRow(e) {
            e.path[3].rows[e.path[3].rows.length-1].remove();

        }
       
        $(document).on("click", ".addNew", function () {
            var empId = '';
            var empName = '';
            var empCountry = '';
            var tbody = $('#tblEmployee .tbody');
            for (var i = 0; i < tbody[0].rows[0].cells.length - 1; i++) {
                if (i == 0)
                    empId = tbody[0].rows[tbody[0].rows.length-1].children[i].children[0].value;
                else if (i == 1)
                    empName = tbody[0].rows[tbody[0].rows.length - 1].children[i].children[0].value;
                else if (i == 2)
                    empCountry = tbody[0].rows[tbody[0].rows.length - 1].children[i].children[0].value;

            }
            var Employee = {
                empId: empId,
                empName: empName,
                empCountry: empCountry
            };
            $.ajax({
                url: "/Home/AddNewEmp",
                data: JSON.stringify(Employee),
                type: "POST",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (result) {
                    GetfreshData();
                    alert(result);
                },
                error: function (result) {
                    alert(result);
                }
            });
        });
        //Edit function.
        $(document).on("click", "#tblEmployee .edit", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find("input").length > 0) {
                    $(this).find("input").show();
                    $(this).find("span").hide();
                }
            });
            row.find(".update").show();
            row.find(".cancel").show();
            row.find(".delete").hide();
            $(this).hide();
        });

        //Cancel fuction.
        $(document).on("click", "#tblEmployee .cancel", function () {
            var htmlrow = $(this).closest("tr");
            $("td", htmlrow).each(function () {
                if ($(this).find("input").length > 0) {
                    var span = $(this).find("span");
                    var input = $(this).find("input");
                    input.val(span.html());
                    span.show();
                    input.hide();
                }
            });
            htmlrow.find(".edit").show();
            htmlrow.find(".delete").show();
            htmlrow.find(".update").hide();
            $(this).hide();
        });

        //update function.
        $(document).on("click", "#tblEmployee .update", function () {
            var tr = $(this).closest("tr");
            var Employee = {};
            $("td", tr).each(function () {
                if ($(this).find("input").length > 0) {
                    var SpanTag = $(this).find("span");
                    var InputTag = $(this).find("input");
                    SpanTag.html(InputTag.val());
                    SpanTag.show();
                    InputTag.hide();
                }
            });
            Employee.empId = tr.find(".empId").find("span").html();
            Employee.empName = tr.find(".empName").find("span").html();
            Employee.empCountry = tr.find(".empCountry").find("span").html();
            $.ajax({
                type: "POST",
                url: "/Home/UpdateEmp",
                data: '{obj:' + JSON.stringify(Employee) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    GetfreshData();
                    alert(result);
                },
                error: function (errormsg) {
                    alert(errormsg);
                }
            });
        });

        function Delele(empId) {
            $.ajax({
                type: "POST",
                url: "/Home/DeleteEmp",
                data: '{empId:' + JSON.stringify(empId) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    GetfreshData();
                    alert(result);
                },
                error: function (errormsg) {
                    alert(errormsg);
                }
            });
        }          
    </script>
</body>
</html>

 

Output Screen of CRUD Operation

Output-Screen

 

Download Compleate Solution from here.

 

I hope this article will help you to learn and implement CRUD Operation in your solution if you like this article please share Us on

Shubham Kumar

Shubham Kumar is a founder of AspNetBugs, .NET Team Leader. He has very good experience with designing and developing enterprise-scale applications. He is exprience in ASP.NET MVC,ASP.NET C#, ASP.NET Core, AngularJS, Web API, EPPlus, SQL, Entity Framework, JavaScript, jQuery, Kendo, Windows services etc.

Thanks for your code is very helpful to me, I have a question, how can we put filters to the grid??
11/6/2021 12:00:00 AM rakesh singh
rakesh singh hey how to solve it
11/7/2021 12:00:00 AM suraj singh