CRUD Operation using Ajax Call in Asp.Net MVC

CRUD Operations in MVC

This article is all about ASP.NET MVC CRUD operations using Ajax Call and Entity Data Model (DB First Approach). This will explain it in baby steps using images. I have also attached a video where you can find the whole things in detail. Basically, this CRUD operation is a part of a project which is a School Management Software. So you can watch that video also.

Lets start.

CRUD means Create Read Update Delete.

Add Class Controller.

Just Right Click on the Controller and then Add the Controller which is highlighted in the image below.

Add ClassMaster Controller

Choose Template

An Index Action Method is added when you add the Controller.

Index Action Method

Adding a View for this Action Method by right Clicking in the Action Method block.

Add View

Then we add a model on the model folder.Basically model is a class where we can define different properties and methods.Where we write the business logics.

Then after i have also added my edmx file where i attach my database and i have also created a database in that database i have added a table ClassMaster.

After that i started writing the code for the ClassMaster model.

namespace SchoolEasy.Web.Areas.School.Models
{
    public class ClassMasterModel
    {
        public int Id { get; set; }
        [Required(ErrorMessage = "Enter Class Name!")]
        public string ClassName { get; set; }
        public int CourseId { get; set; }
        public List<ClassList> ClassList { get; set; }
    }

    public class ClassList
    {
        public int Id { get; set; }
        public string ClassName { get; set; }
        public string CourseName { get; set; }
    }
}

After that I start coding in the Index Action Method for the Dropdown which i used in my Class Master Form where i select the Course and after the Class Name is entered.In which SchoolAppEntities db = new SchoolAppEntities() is the entity part which generate a connection between the database.

 SchoolAppEntities db = new SchoolAppEntities();
        // GET: School/ClassMaster
        public ActionResult Index()
        {
            ClassMasterModel model = new ClassMasterModel();
            string SchoolCode = Convert.ToString(Session["SchoolCode"]);
            ViewBag.CourseId = new SelectList((from p in db.CourseMasters where p.SchoolCode == SchoolCode select p).ToList(), "CourseId", "CourseName");
            return View(model);
        }

After that we write some code for the view. Where I added only one view for Add and Update Class and also added a partial view for the class list.

@model SchoolEasy.Web.Areas.School.Models.ClassMasterModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Dashboard.cshtml";
}

<section class="content">
    <div class="row">
        <!-- left column -->
        <div class="col-md-12">
            <!-- general form elements -->
            <div class="box box-primary">
                <div class="box-header with-border">
                    <h3 class="box-title">Class Master</h3>
                </div>
                <!-- /.box-header -->
                <!-- form start -->
                @using (Html.BeginForm("Index", "ClassMaster", FormMethod.Post, new { area = "School", @id = "frm_Class" }))
                {
                    <div id="formbody">
                        @Html.AntiForgeryToken()
                        <div class="box-body">
                            <div class="form-group">
                                <label>Select Course Name</label>
                                @Html.HiddenFor(m => m.Id)
                                @Html.DropDownList("CourseId", null, "Select Course", htmlAttributes: new { @class = "form-control" })
                                @Html.ValidationMessageFor(m => m.CourseId, "", new { @class = "text-danger" })
                            </div>
                            <div class="form-group">
                                <label>Class Name</label>
                                @Html.EditorFor(m => m.ClassName, new { htmlAttributes = new { @placeholder = "Enter Class Name" ,@class="form-control"} })
                                @Html.ValidationMessageFor(m => m.ClassName, "", new { @class = "text-danger" })
                            </div>
                        </div>
                    </div>
                    <div id="TableCLass" style="display:none;">
                        @Html.Partial("_ClassList", @Model)
                    </div>
                    <!-- /.box-body -->
                    <div class="box-footer">
                        <a href="#" id="btnsave" onclick="return SaveClass()" class="btn-success btn-sm" data-toggle="tooltip" title="Save"> <i class="fa fa-save "></i> <span>Save</span></a>
                        <a href="#" id="btnedit" onclick="return UpdateClass()" class="btn-success btn-sm hidden" data-toggle="tooltip" title="Update"> <i class="fa fa-save "></i> <span>Update</span></a>
                        <a href="#" onclick="return ViewClassList()" class="btn-primary btn-sm" data-toggle="tooltip" title="View"> <i class="fa fa-list-ul "></i> <span>View</span></a>
                        <a href="#" onclick="return Clear()" class="btn-default btn-sm" data-toggle="tooltip" title="Clear"> <i class="fa fa-eraser "></i> <span>Clear</span></a>
                    </div>
                }
            </div>
            <!-- /.box -->
        </div>
        <!--/.col (left) -->
    </div>
    <!-- /.row -->
</section>

After that I create a function for saving the data and that function uses the Ajax call for further functionality.

 function SaveClass() {
        var formdata = $('#frm_Class').get(0);
        var data = new FormData(formdata);
        $.ajax({
            type: 'POST',
            url:'@Url.Action("SaveClass", "ClassMaster",new { area="School"})',
            processData: false,
            contentType: false,
            data: data,
            success: function (Result) {
                if (Result.IsSuccess) {
                    swal(Result.msg,"", "success");
                    $('#ClassName').val('');
                    $('#Id').val('');
                    $('#CLassName').val('');
                    $("#CourseId").prop('selectedIndex', 0);
                }
                else {
                    swal(Result.msg, "warning")
                }
            },
            error: function (Error) {

            }

        })
    }

And the Controller Side code for Saving the data.

   [HttpPost]
        public JsonResult SaveClass(ClassMasterModel model)
        {
            var IsSuccess = false;
            var msg = "";
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            try
            {
                if(ModelState.IsValid)
                {
                    var checkCLassName = db.ClassMasters.Where(x => x.ClassName.ToUpper() == model.ClassName.ToUpper().Trim()).Count();
                    if (checkCLassName == 0)
                    {
                        ClassMaster classM = new ClassMaster();
                        classM.ClassName = model.ClassName;
                        classM.CourseId = model.CourseId;
                        db.ClassMasters.Add(classM);
                        db.SaveChanges();
                        IsSuccess = true;
                        msg = "Data Saved Successfully";
                    }
                    else
                    {
                        IsSuccess = false;
                        msg = "Class Name Already Exists";
                    }
                }
                else
                {
                    IsSuccess = false;
                    msg = "Validation Error";
                }            
            }
            catch (Exception ex)
            {
                IsSuccess = false;
                msg = ex.Message;
            }
            var jsonData = new { IsSuccess, msg };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

After that if I want to see my list of class which I added into the database then for that I added a partial view.For calling the partial view the code is given below.

  function ViewClassList() {
        $('#formbody').hide();
        $.ajax({
            type: 'POST',
            url:'@Url.Action("ViewClassList", "ClassMaster",new { area="School"})',
            success: function (Result) {
                $('#TableCLass').show();
                $('#TableCLass').html('');
                $('#TableCLass').html(Result);
            },
            error: function (Error) {

            }

        })
    }
 [HttpPost]
        public ActionResult ViewCLassList()
        {
            ClassMasterModel model = new ClassMasterModel();
            var data = (from p in db.ClassMasters
                        select new ClassList
                        {
                            Id=p.ClassId,
                            ClassName=p.ClassName,
                            CourseName=p.CourseMaster.CourseName
                        }).ToList();

            model.ClassList = data;
            return PartialView("_CLassList", model);
        }

Partial View code for showing the user the list of classes which is saved in the database.

@model SchoolEasy.Web.Areas.School.Models.ClassMasterModel

@if (Model.ClassList != null && Model.ClassList.Count > 0)
{
    <div class="box-body table-responsive no-padding">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>Course Name</th>
                    <th>Class Name</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                @for (int i = 0; i < Model.ClassList.Count; i++)
                {
                    <tr>
                        <td>@Html.DisplayFor(model => model.ClassList[i].CourseName)</td>
                        <td>@Html.DisplayFor(model => model.ClassList[i].ClassName)</td>
                        <td>
                            <a href="#" class="btn btn-warning" onclick="EditClass(@Model.ClassList[i].Id)"><i class="fa fa-pencil"></i></a> 
                            <a href="#" class="btn btn-danger" onclick="DeleteClass(@Model.ClassList[i].Id)"><i class="fa fa-trash"></i></a>
                        </td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
}

After that if I want to edit some data then we have to call a function for editing the data.


    function EditClass(id) {
        $('#TableCLass').hide();
        $('#formbody').show();
        $.ajax({
            type: 'GET',
            url: '@Url.Action("EditCLass", "ClassMaster",new { area="School"})',
            datatype: "JSON",
            data: { id: id },
            success: function (Result) {
                debugger
                $('#Id').val(Result.Id);
                $('#ClassName').val(Result.ClassName);
                $("#CourseId").val(Result.CourseId);
                $('#btnsave').hide();
                $('#btnedit').removeClass("hidden");
                $('#btnedit').show();
            },
            error: function (Error) {

            }

        })
    }

Controller Side for Editing the data.

  public ActionResult EditClass(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new HttpNotFoundResult("Class With this Name Not Found.Try Again.");
            }
            try
            {
                string SchoolCode = Convert.ToString(Session["SchoolCode"]);
                int ClassId = 0;
                int.TryParse(id, out ClassId);
                ClassMaster model = db.ClassMasters.Find(ClassId);
                ClassMasterModel cm = new ClassMasterModel();
                cm.Id = model.ClassId;
                cm.ClassName = model.ClassName;
                cm.CourseId = model.CourseId;
                ViewBag.CourseId = new SelectList((from p in db.CourseMasters where p.SchoolCode == SchoolCode select p), "CourseId", "CourseName", model.CourseId).ToList();
                return Json(cm, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                TempData["msg"] = "Some Error Occurred.Unable to Fetch Data.Try Again. " + ex.Message;
                return RedirectToAction("Index");
            }
        }

After binding all the data to the respective fields If I want to update the data then we have to call a Update Class function which is same as that of the Save Class Function.

function UpdateClass() {
        var formdata = $('#frm_Class').get(0);
        var data = new FormData(formdata);
        $.ajax({
            type: 'POST',
            url:'@Url.Action("UpdateClass", "ClassMaster",new { area="School"})',
            processData: false,
            contentType: false,
            data: data,
            success: function (Result) {
                if (Result.isSuccess) {
                    swal(Result.message,"", "success");
                    $('#ClassName').val('');
                    $('#Id').val('');
                    $('#CLassName').val('');
                    $("#CourseId").prop('selectedIndex', 0);
                    $('#btnsave').show();
                    $('#btnedit').addClass("hidden");
                    $('#btnedit').hide();
                }
                else {
                    swal(Result.message, "warning")
                }
            },
            error: function (Error) {

            }

        })
    }

Controller Side code for updating the data.

 [HttpPost]
        public JsonResult UpdateClass(ClassMasterModel cm)
        {
            var isSuccess = false;
            var message = "";
            try
            {
                if (cm.Id == 0)
                {
                    isSuccess = false;
                    message = " Class With this Name Not Found.Try Again.";
                }
                ClassMaster model = db.ClassMasters.Find(cm.Id);
                model.CourseId = cm.CourseId;
                model.ClassName = cm.ClassName.Trim();
                db.Entry(model).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
                isSuccess = true;
                message = "Data Modified Successfully";
                return Json("Data Modified Successfully", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                isSuccess = false;
                message = ex.Message;
            }
            var jsonData = new { isSuccess, message };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

If we want to delete the from the database then we have to click the detail button and for that we have to call a function for deleting the data.

function DeleteClass(id) {
        $('#TableCLass').hide();
        $('#formbody').show();
        var id = id;
        var flag = confirm('Are you sure you want to delete this record?')
        if (flag) {
            $.ajax({
                url: '@Url.Action("DeleteClass", "ClassMaster",new {area="School"})',
                type: "GET",
                datatype: "JSON",
                data: { id: id },
                success: function (Result) {
                    if (Result.isSuccess) {
                        swal(Result.message, "", "success");
                        $('#TableCLass').html('');
                    }
                    else {
                        swal(Result.message, "", "error");
                        $('#TableCLass').html('');
                    }
                }
            })
        }
    }

Controller Side for Deleting the Data.

 public ActionResult DeleteClass(string id)
        {
            var isSuccess = false;
            var message = "";
            if (string.IsNullOrEmpty(id))
            {
                return new HttpNotFoundResult("Class With this Name Not Found.Try Again.");
            }
            try
            {
                int ClassId = 0;
                int.TryParse(id, out ClassId);
                ClassMaster model = db.ClassMasters.Find(ClassId);
                db.Entry(model).State = System.Data.Entity.EntityState.Deleted;
                db.SaveChanges();
                isSuccess = true;
                message = "Class Deleted Successfully";
            }
            catch (Exception ex)
            {
                var ErrMsg = "";
                if (ex.InnerException != null)
                {
                    if (ex.InnerException.InnerException == null)
                    {
                        ErrMsg = ex.InnerException.Message;
                    }
                    else
                    {
                        ErrMsg = ex.InnerException.InnerException.Message;
                    }
                }
                else
                {
                    ErrMsg = ex.Message;
                }
                if (ErrMsg.Contains("The DELETE statement conflicted with the REFERENCE constraint "))
                {
                    ErrMsg = "This information is already being used in system somewhere, can't be deleted!";
                }
                isSuccess = false;
                message = ErrMsg;
            }
            var jsonData = new { isSuccess, message };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

And If we want to clear or reset the form then we have to click the Clear button.

 function Clear() {
        $('#ClassName').val('');
        $('#Id').val('');
        $('#CLassName').val('');
        $("#CourseId").prop('selectedIndex', 0);
        $('#btnsave').show();
        $('#btnedit').addClass("hidden");
        $('#btnedit').hide();
        $('#TableCLass').hide();
        $('#formbody').show();
    }

If you found this post interesting then you can check the below video link for more knowledge.

0 0 vote
Article Rating

Subscribe
Notify of
guest
1 Comment
oldest
newest most voted
Inline Feedbacks
View all comments
Suman Kumar Keshari
Suman Kumar Keshari
1 year ago

Thank you sir for this. Especially your video tutorial is awesome.

1
0
Would love your thoughts, please comment.x
()
x