Thumb

CRUD Operations In MVC Using Jquery Ajax | Part-3 Data Save,Update & Delete In Database

10/20/2019 12:00:00 AM

Download Project (Full Project)

Step-1

In this part i will show how to CRUD Operations In MVC Using Jquery  Ajax. First open visual studio then opens our existing project where we are working. In index view we need to write some html code and also use bootstrap class. In this view we go to use bootstrap popup model for Registration. In this code when we click the button then jQuery call the modal by the id and this modal show the same view on popup.  In this view we use Ajax post. When id is zero it is add else Edit. Now write some html code for delete. Delete also pass the id by the Ajax post and it also use confirmation popup. Given bellow the view code:

@model FullCRUDImplementationWithJquery.Models.StudentViewModel
@{
    Layout = null;
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />

<div class="container" style="margin-top:3%">
    <a href="#" class="btn btn-info" onclick="AddNewStudent(0)">Add New Student</a> <br /><br />

    <table class="table table-striped">
        <thead>
            <tr>
                <th>Student ID</th>
                <th>Student Name</th>
                <th>Email</th>
                <th>Department</th>
                <th>Action(Edit)</th>
                <th>Action(Delete)</th>

            </tr>
        </thead>
        <tbody id="SetStudentList">
            <tr id="LoadingStatus" style="color:red"></tr>
        </tbody>
    </table>

    @*Create A Popup Modal With Registration Form For Add Or Edit Student Record*@

    <div class="modal fade" id="MyModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <a href="#" class="close" data-dismiss="modal">&times;</a>
                    <h4 id="ModalTitle"></h4>
                </div>
                <div class="modal-body">
                    <form id="form">
                        <fieldset id="SubmitForm">
                            @Html.HiddenFor(m => m.StudentId, new { @id = "StuId" })
                            <div class="form-group">
                                @Html.TextBoxFor(m => m.StudentName, new { @id = "StuName", @class = "form-control", @placeholder = "Name*" })
                            </div>
                            <div class="form-group">
                                @Html.TextBoxFor(m => m.Email, new { @id = "Email", @class = "form-control", @placeholder = "Email*" })
                            </div>
                            <div class="form-group">
                                @Html.DropDownListFor(m => m.DepartmentId, ViewBag.ListOfDepartment as SelectList, "--Select Dept--", new { @id = "DropDwn", @class = "form-control" })
                            </div>
                            <div class="form-group">
                                <a href="#" class="btn btn-block btn-danger" id="SaveStudentRecord">Save</a>
                            </div>

                        </fieldset>
                    </form>
                </div>
            </div>
        </div>
    </div>

    @*Create A PopUp Modal For DeleteConfirmation*@

    <div class="modal fade" id="DeleteConfirmation">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <a href="#" class="close" data-dismiss="modal">&times;</a>
                    <h4>Delete Student Record</h4>
                </div>
                <div class="modal-body">
                    <h4>Are You Sure? You Want To Delete This Record.</h4>
                </div>
                <div class="modal-footer">
                    <a href="#" class="btn btn-primary" data-dismiss="modal" id="r">Cancle</a>
                    <a href="#" class="btn btn-danger" onclick="ConfirmDelete()">Confirm</a>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $("#LoadingStatus").html("Loading....");
    $.get("/Home/GetStudentList", null, DataBind);
    function DataBind(StudentList) {
        var SetData = $("#SetStudentList");
        for (var i = 0; i < StudentList.length; i++) {
            var Data = "<tr class='row_" + StudentList[i].StudentId + "'>" +
                "<td>" + StudentList[i].StudentId + "</td>" +
                "<td>" + StudentList[i].StudentName + "</td>" +
                "<td>" + StudentList[i].Email + "</td>" +
                "<td>" + StudentList[i].DepartmentName + "</td>" +
                "<td>" + "<a href='#' class='btn btn-warning' onclick='EditStudentRecord(" + StudentList[i].StudentId + ")' ><span class='glyphicon glyphicon-edit'></span></a>" + "</td>" +
                "<td>" + "<a href='#' class='btn btn-danger' onclick='DeleteStudentRecord(" + StudentList[i].StudentId + ")'><span class='glyphicon glyphicon-trash'></span></a>" + "</td>" +
                "</tr>";
            SetData.append(Data);
            $("#LoadingStatus").html(" ");

        }
    }

    //Show The Popup Modal For Add New Student

    function AddNewStudent(StudentId) {
        $("#form")[0].reset();
        $("#StuId").val(0);
        $("#DropDwn option:selected").text("--Select Dept--");
        $("#ModalTitle").html("Add New Student");
        $("#MyModal").modal();

    }

    //Show The Popup Modal For Edit Student Record

    function EditStudentRecord(StudentId) {
        var url = "/Home/GetStudentById?StudentId=" + StudentId;
        $("#ModalTitle").html("Update Student Record");
        $("#MyModal").modal();
        $.ajax({
            type: "GET",
            url: url,
            success: function (data) {
                var obj = JSON.parse(data);
                $("#StuId").val(obj.StudentId);
                $("#StuName").val(obj.StudentName);
                $("#Email").val(obj.Email);
                $("#DropDwn option:selected").text(obj.tblDepartment.DepartmentName);
                $("#DropDwn option:selected").val(obj.DepartmentId);

            }
        })
    }

    $("#SaveStudentRecord").click(function () {
        var data = $("#SubmitForm").serialize();
        $.ajax({
            type: "Post",
            url: "/Home/SaveDataInDatabase",
            data: data,
            success: function (result) {
                alert("Success!..");
                window.location.href = "/Home/index";
                $("#MyModal").modal("hide");

            }
        })
    })

    //Show The Popup Modal For DeleteComfirmation
    var DeleteStudentRecord = function (StudentId) {
        $("#StuId").val(StudentId);
        $("#DeleteConfirmation").modal("show");
    }
    var ConfirmDelete = function () {
        var StuId = $("#StuId").val();
        $.ajax({
            type: "POST",
            url: "/Home/DeleteStudentRecord?StudentId=" + StuId,
            success: function (result) {
                $("#DeleteConfirmation").modal("hide");
                $(".row_" + StuId).remove();
            }
        })
    }
</script>

Step-2 

Now Home controller has some method which is responsible to crude operation. “GetStudentList” method pass the student list on the view. “SaveDataInDatabase”  data method restive the object and when id is zero then it will be add into database otherwise it will be edit. “DeleteStudentRecord” method are responsible to set the value in bootstrap modal then when edit button click then it post the value in the “SaveDataInDatabase” method again. Then its id is not zero it will be edit. Given bellow the controller code:

using FullCRUDImplementationWithJquery.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FullCRUDImplementationWithJquery.Controllers
{
    public class HomeController : Controller
    {
        MVCTutorialEntities db = new MVCTutorialEntities();
        public ActionResult Index()
        {
            List<tblDepartment> DeptList = db.tblDepartments.ToList();
            ViewBag.ListOfDepartment = new SelectList(DeptList, "DepartmentId", "DepartmentName");
            return View();
        }

        public JsonResult GetStudentList()
        {
            List<StudentViewModel> StuList = db.tblStudents.Where(x => x.IsDeleted == false).Select(x => new StudentViewModel
            {
                StudentId = x.StudentId,
                StudentName = x.StudentName,
                Email = x.Email,
                DepartmentName = x.tblDepartment.DepartmentName
            }).ToList();

            return Json(StuList, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetStudentById(int StudentId)
        {
            tblStudent model = db.tblStudents.Where(x => x.StudentId == StudentId).SingleOrDefault();
            string value = string.Empty;
            value = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });
            return Json(value, JsonRequestBehavior.AllowGet);
        }

        public JsonResult SaveDataInDatabase(StudentViewModel model)
        {
            var result = false;
            try
            {
                if (model.StudentId > 0)
                {
                    tblStudent Stu = db.tblStudents.SingleOrDefault(x => x.IsDeleted == false && x.StudentId == model.StudentId);
                    Stu.StudentName = model.StudentName;
                    Stu.Email = model.Email;
                    Stu.DepartmentId = model.DepartmentId;
                    db.SaveChanges();
                    result = true;
                }
                else
                {
                    tblStudent Stu = new tblStudent();
                    Stu.StudentName = model.StudentName;
                    Stu.Email = model.Email;
                    Stu.DepartmentId = model.DepartmentId;
                    Stu.IsDeleted = false;
                    db.tblStudents.Add(Stu);
                    db.SaveChanges();
                    result = true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteStudentRecord(int StudentId)
        {
            bool result = false;
            tblStudent Stu = db.tblStudents.SingleOrDefault(x => x.IsDeleted == false && x.StudentId == StudentId);
            if (Stu != null)
            {
                Stu.IsDeleted = true;
                db.SaveChanges();
                result = true;
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}

Step-3

Now build and run the project.

About Teacher

Reza Karim

Software Engineer

More about him