CRUD Operation Using Jquery Ajax In ASP.NET MVC

CRUD operation with jquery ajax in asp.net mvc

In this post we will discuss about how to do CRUD with the help of jquery ajax. here we will take two file one is .cshtml file and one is .cs file. .cshtml file is our view and .cs file will handle DB operation. In this example I am creating a static list for creating records.

I have .cs controller file this file name is JqueryAjaxController.cs. And .cshtml file this file name is Index.cshtml.


JqueryAjaxController.cs :-

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

using System.Web.Mvc;


namespace Learn_mvc.Controllers

{

    public class JqueryAjaxController : Controller

    {

        private static List<JAEmp> emps = new List<JAEmp>() {

                new JAEmp(){ EmpId="101", EmpName="Aman", EmpSalary="1000"},

                new JAEmp(){ EmpId="102", EmpName="Bman", EmpSalary="2000"},

                new JAEmp(){ EmpId="103", EmpName="Cman", EmpSalary="3000"},

                new JAEmp(){ EmpId="104", EmpName="Dman", EmpSalary="4000"}

            };


        public JqueryAjaxController()

        {

        }

        public ActionResult Index()

        {

            return View();

        }


        public ActionResult GetEmps()

        {

            object data = "";

            var msg = "";

            if (emps != null)

            {

                data = emps;

                msg = "SUCCESS";

            }

            var json = new { Data = data, Message = msg };

            return Json(json, JsonRequestBehavior.AllowGet);

        }


        public ActionResult AddEmp(JAEmp emp)

        {

            object data = false;

            var msg = "";

            if (ModelState.IsValid)

            {

                emp.EmpId = Guid.NewGuid().ToString();

                emps.Add(emp);

                data = true;

                msg = "SUCCESS";

            }

            var json = new { Data = data, Message = msg };

            return Json(json, JsonRequestBehavior.AllowGet);

        }


        public ActionResult DeleteEmp(string empId)

        {

            object data = false;

            var msg = "";

            if (empId != null && empId != "")

            {

                var obj = emps.Where(x => x.EmpId == empId).FirstOrDefault();

                if (obj != null)

                {

                    emps.Remove(obj);

                    data = true;

                    msg = "SUCCESS";

                }

            }

            var json = new { Data = data, Message = msg };

            return Json(json, JsonRequestBehavior.AllowGet);

        }


        public ActionResult UpdateEmp(string empId, JAEmp emp)

        {

            object data = false;

            var msg = "";

            if (empId != null && empId != "")

            {

                if (ModelState.IsValid)

                {

                    var obj = emps.Where(x => x.EmpId == empId).FirstOrDefault();

                    if (obj != null)

                    {

                        obj.EmpName = emp.EmpName;

                        obj.EmpSalary = emp.EmpSalary;

                        data = true;

                        msg = "SUCCESS";

                    }

                } 

            }

            var json = new { Data = data, Message = msg };

            return Json(json, JsonRequestBehavior.AllowGet);

        }

    }


    public class JAEmp

    {

        public string EmpId { get; set; }


        [Required]

        public string EmpName { get; set; }


        [Required]

        public string EmpSalary { get; set; }

    }

}


Index.cshtml :-

@{

    ViewBag.Title = "Index";

}

<style>

    table, th, td {

        border: 1px solid black;

        border-collapse: collapse;

        padding: 10px;

    }

</style>

<div id="divAddEmp">

    <form id="empForm">

        <table>

            <tbody>

                <tr>

                    <td>

                        <div>

                            <span>Employee Name</span>

                            <input type="text" id="txtEmpName" />

                        </div>

                    </td>

                    <td>

                        <div>

                            <span>Employee Salary</span>

                            <input type="text" id="txtEmpSal" />

                        </div>

                    </td>

                    <td>

                        <button type="button" onclick="AddEmp()" id="btnAdd">Add</button>

                        <button type="button" id="btnUpdateEmp" style="display:none;">Update</button>

                    </td>

                </tr>

            </tbody>

        </table>

    </form>

</div>

<br/>

<div id="divEmpList">

    <table>

        <thead>

            <tr>

                <th>Employee Name</th>

                <th>Employee Salary</th>

                <th>Action</th>

                <th>Action</th>

            </tr>

        </thead>

        <tbody>

        </tbody>

    </table>

</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

    <script>

        function GetEmps() {

            var type = "GET";

            var url = "/JqueryAjax/GetEmps";

            AjaxCall(type, url).then(function (res) {

                if (res.Message == "SUCCESS") {

                    $("#divEmpList > table > tbody").empty();

                    var data = res.Data;

                    $.each(data, function (index, item) {

                        //var empObj = JSON.stringify(item).replace(/"/g, '&quot;');

                        var updateBtnId = "btnShowEmpOnUpdate" + index;

                        var deleteBtnId = "btnDeleteEmp" + index;

                        var html = `<tr>

                                        <td>` + item.EmpName + `</td>

                                        <td>` + item.EmpSalary + `</td>

                                        <td>

                                            <button type="button" id="`+ updateBtnId+`">Update</button>

                                        </td>

                                        <td>

                                            <button type="button" id="`+ deleteBtnId+`">Delete</button>

                                        </td>

                                    </tr>`;

                        

                        $("#divEmpList > table > tbody").append(html);


                        $("#" + updateBtnId).click(function () {

                            ShowEmp(item);

                        });

                        $("#" + deleteBtnId).click(function () {

                            DeleteEmp(item.EmpId);

                        });

                    });

                }

            }).catch(function (err) {

                alert("Oops something is wrong...");

            });

        }


        function ShowEmp(emp) {

            $("#txtEmpName").val(emp.EmpName);

            $("#txtEmpSal").val(emp.EmpSalary);

            $("#btnUpdateEmp").show();

            $("#btnUpdateEmp").click(function () {

                var empName = $("#txtEmpName").val().trim();

                var empSal = $("#txtEmpSal").val().trim();

                var empObj = { EmpName: empName, EmpSalary: empSal };

                UpdateEmp(emp.EmpId, empObj);

            });

            $("#btnAdd").hide();

        }


        function UpdateEmp(empId,emp) {

            if (empId != null && empId.trim() != "") {

                var type = "POST";

                var url = "/JqueryAjax/UpdateEmp?empId=" + empId;

                var obj = { EmpName: emp.EmpName, EmpSalary: emp.EmpSalary };

                var jsonObj = JSON.stringify(obj);

                AjaxCall(type, url, jsonObj).then(function (res) {

                    if (res.Message == "SUCCESS") {

                        var data = res.Data;

                        if (data) {

                            $("#empForm")[0].reset();

                            $("#btnAdd").show();

                            $("#btnUpdate").hide();

                            GetEmps();

                        }

                    }

                }).catch(function (err) {

                    alert("Oops something is wrong...");

                });

            }

        }


        function DeleteEmp(empId) {

            if (empId != null && empId.trim() != "") {

                var type = "GET";

                var url = "/JqueryAjax/DeleteEmp?empId=" + empId;

                AjaxCall(type, url).then(function (res) {

                    if (res.Message == "SUCCESS") {

                        var data = res.Data;

                        if (data) {

                            GetEmps();

                        }

                    }

                }).catch(function (err) {

                    alert("Oops something is wrong...");

                });

            }

        }


        function AddEmp() {

            var empName = $("#txtEmpName").val().trim();

            var empSal = $("#txtEmpSal").val().trim();

            if (empName != "" && empSal != "") {

                var type = "POST";

                var url = "/JqueryAjax/AddEmp";

                var obj = { EmpName: empName, EmpSalary: empSal };

                var jsonObj = JSON.stringify(obj);

                AjaxCall(type, url, jsonObj).then(function (res) {

                    if (res.Message == "SUCCESS") {

                        var data = res.Data;

                        if (data) {

                            GetEmps();

                        }

                    }

                }).catch(function (err) {

                    alert("Oops something is wrong...");

                });

            }

        }


        function AjaxCall(type, url, data = "") {

            return new Promise(function (resolve, reject) {

                $.ajax({

                    type: type,

                    url: url,

                    data: data,

                    contentType: "application/json; charset=utf-8",

                    dataType: "json",

                    success: function (res, status, xhr) {

                        resolve(res)

                    },

                    error: function (err, status, xhr) {

                        reject(err)

                    }

                });

            });

        }

    </script>

    <script>

        $(function () {

            GetEmps();

        });

    </script>

Comments

Popular posts from this blog

Call CRUD(GET, POST, PUT, DELETE) API using WebClient in c#

Asp.Net MVC 5 authentication and authorization using claims principal