CRUD Operations In MVC Using Entity Framework With AJAX Call, jQuery, And All Validations

Introduction 

This article demonstrates how to create and use an insert, update and delete recored using asp.net MVC with C# technology. In this article first of all I'll explain the mvc and also how to make an ajax call in mvc with the server side call, then I'll explain Entity framework and how to make a validation in your project using jquery and javascript.

C-Create-POST
R - Read - GET
U - Update - PUT
D - Delete – DELETE
 
What is MVC?

The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the Model, the View, and the Controller. Each of these components is built to handle specific development aspects of an application. MVC is one of the most frequently used industry-standard web development frameworks to create scalable and extensible projects.

MVC
  1. Model - The Model is the part of the application that handles the logic for the application data.Often model objects retrieve data (and store data) from a database.
  2. View is the parts of the application that handles the display of the data. Most often the views are created from the model data.
  3. Controller is the part of the application that handles user interaction.Typically controllers read data from a view, control user input, and send input data to the model.
 What is Entity Framework?
  • Object/Relational Mapping (ORM) framework
  • Work with database as domain-specific objects
  • Retrieve and manipulate data as strongly typed objects
What is AJAX Call?

Your method returns JSON result. This is MVC specific and you cannot use it in a webforms application if you want to call methods in the code behind. 
  1. public JsonResult AddToCart(int PID)  
  2.         {  
  3.             var result = new jsonMessage();  
  4.             try  
  5.             {  
  6.   
  7.                 Mst_Product _Mst_Product = context.Mst_Product.Where(t => t.PID == PID).FirstOrDefault();  
  8.   
  9.                 //define the model of crt  
  10.                 Cart _Cart = new Cart();  
  11.                 _Cart.PID = PID;  
  12.                 _Cart.Quantity = 1;  
  13.                 _Cart.DateTime = System.DateTime.Now;  
  14.                 _Cart.TotalPrice = Convert.ToDouble(_Mst_Product.Price);  
  15.   
  16.                 context.Carts.Add(_Cart);  
  17.                 result.Message = "your product has been Added in to cart..";  
  18.                 result.Status = true;  
  19.   
  20.                 context.SaveChanges();  
  21.   
  22.   
  23.             }  
  24.             catch (Exception ex)  
  25.             {  
  26.                 ErrorLogers.ErrorLog(ex);  
  27.                 result.Message = "We are unable to process your request at this time. Please try again later.";  
  28.                 result.Status = false;  
  29.             }  
  30.             return Json(result, JsonRequestBehavior.AllowGet);  
  31.         }  

  1. $.ajax({  
  2.            url: '@Url.Action("AddToCart", "Product")',  
  3.                type: 'POST',  
  4.                data: JSON.stringify({ "PID": parseInt(PID) }),  
  5.                dataType: "json",  
  6.                contentType: "application/json; charset=utf-8",  
  7.                success: function (result) {  
  8.                    $('#dvLoader').hide();  
  9.   
  10.                    if (result.Status == "True") {  
  11.                        toastr.success(result.Message);  
  12.                        clear();  
  13.                        display();  
  14.                    }  
  15.                    else {  
  16.                        toastr.success(result.Message);  
  17.                        clear();  
  18.                        display();  
  19.   
  20.                    }  
  21.                }  
  22.            });  
Now start your web app..
 
Step 1 : Open your Visual Studio (the Visual Studio Version should be greater than or equal to 12) and add an MVC internet application as in the following,

MVC

MVC

I have given it the name "Datatable_Demo".

Step 2 : Create the new Database for this project Name: "PMS" and make the new table of "Product" with property of this table. Make Identity "Yes." Ihave already give one script file for the making of PMS database as well as Table.

MVC

Step 3 : Add the Model in this project. right click on your project then click on the Data and choose the ADO.Net Entity Data Model

MVC

Select this EF designer from the database.

MVC
 
MVC

Step 4 : Make the connction of this database to this project  click to connect database and then write your server name on textbox and then select your database name from the dropdown,check if your connection is successful or not.

MVC

Step 5 : 
Add new controller in this project , right click on controller and add a new controller name for this controller 

MVC
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace DataTable_Demo.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         //  
  13.         // GET: /Home/  
  14.          
  15.         public ActionResult Index()  
  16.         {  
  17.             return View();  
  18.         }  
  19.          
  20.          
  21.     }  
  22. }  

Step 6 : Add view of this Action Result Method. You can add view without layout and also with the layout. 

MVC

Step 7 : Add Css of bootstrap, toaster css, datatable css and bootrapJs, jqueryjs, datatablejs, toasterjs, bootboxjs, which is described below.  

  1. <!-- Latest compiled and minified CSS -->    
  2. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">    
  3.     
  4. <!-- jQuery library -->    
  5. <script src="//code.jquery.com/jquery-1.12.4.js"></script>    
  6.     
  7. <!-- Latest compiled JavaScript -->    
  8. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>    
  9.     
  10. <!-- add thids links for the error message-->    
  11. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/css/toastr.css" />    
  12. <script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/1.3.1/js/toastr.js"></script>    
  13.     
  14.     
  15. <!--add this link for the datatable-->    
  16. <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />    
  17. <link href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.csss" rel="stylesheet" />    
  18.     
  19. <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>    
  20. <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>    
  21.     
  22. <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js" integrity="sha256-4F7e4JsAJyLUdpP7Q8Sah866jCOhv72zU5E8lIRER4w=" crossorigin="anonymous"></script>    
Step 8 : Add textbox label and also button in this view like this. 
  1. <div class="col-md-12">  
  2.     <div class="col-md-4"></div>  
  3.     <div class="col-md-4">  
  4.         <div class="col-md-12">  
  5.             <label>Product Name :</label>  
  6.             <input class="form-control required" type="text" id="txtName" required />  
  7.         </div>  
  8.         <div class="col-md-12">  
  9.             <label>Product Descreption :</label>  
  10.             <textarea class="form-control required" id="txtDesc"></textarea>  
  11.         </div>  
  12.         <div class="col-md-12">  
  13.             <label>Product Price :</label>  
  14.             <input class="form-control required" onkeypress = "return isNumberKey(event)" id="txtPrice" type="text" required />  
  15.         </div>  
  16.         <div class="col-md-12">  
  17.             <br />  
  18.             <input id="btnSave" class="btn btn-success" type="button" value="Save Product" />  
  19.             <input id="btnCancel" class="btn btn-danger" type="button" value="Cancel" />  
  20.   
  21.         </div>  
  22.   
  23.     </div>  
  24.     <div class="col-md-4"></div>  
  25.   
  26.   
  27.   
  28. </div>  
Step 9 : Add the hidden file for the stored Product_id for the feature use.
  1. <input type="hidden" id="hdnPID" value="0" />  
Step10

Add the Loader in this view
 
  1. <div id="dvLoader" class="LoadingDiv" style="display: none;">  
  2.     <table style="height: 100%; margin: auto;">  
  3.         <tr>  
  4.             <td style="vertical-align: middle;">  
  5.                 <center>  
  6.                         <img src="http://www.girlsgotit.org/images/ajax-loader.gif"  alt="Loading" />  
  7.                     </center>  
  8.             </td>  
  9.         </tr>  
  10.     </table>  
  11. </div>   
 Add the style of this loader in this view
  1. <style>
  2. .LoadingDiv {  
  3.            top: 0;  
  4.            left: 0;  
  5.            position: fixed;  
  6.            opacity: 0.97;  
  7.            z-index: 10000000;  
  8.            background: Black;  
  9.            height: 100%;  
  10.            width: 100%;  
  11.            margin: auto;  
  12.        } 
  13. </style> 
Step 10 :  Make the AJAX Call for saving and updating the product details in the table in this view.  
  1. <script type="text/javascript">    
  2.         
  3.     $(document).ready(function () {    
  4.  windowResize();    
  5.         $(window).resize(function () {    
  6.             windowResize();    
  7.         });    
  8.         $('#toast-container').find('.toast-top-center').removeClass('.toast-top-center');    
  9.         toastr.options = {    
  10.             "closeButton"true,    
  11.             'autoWidth'false,    
  12.             "debug"false,    
  13.             "newestOnTop"true,    
  14.             "progressBar"true,    
  15.             "positionClass""toast-top-center",    
  16.             "preventDuplicates"false,    
  17.             "onclick": null,    
  18.             "showDuration""300",    
  19.             "hideDuration""1000",    
  20.             "timeOut""3000",    
  21.             "extendedTimeOut""1000",    
  22.             "showEasing""swing",    
  23.             "hideEasing""linear",    
  24.             "showMethod""fadeIn",    
  25.             "hideMethod""fadeOut"    
  26.         }    
  27.     
  28.         $("#btnSave").click(function () {    
  29.             var PID = $("#hdnPID").val();    
  30.             var Name = $("#txtName").val();    
  31.             var Desc = $("#txtDesc").val();    
  32.             var Price = parseFloat($("#txtPrice").val()).toFixed(2);    
  33.             if (CheckRequiredFields()) {    
  34.     
  35.                 $('#dvLoader').show();    
  36.                 $.ajax({    
  37.                     url: '@Url.Action("SaveAndUpdateProduct", "Home")',    
  38.                         type: 'POST',    
  39.                         data: JSON.stringify({ "PID": parseInt(PID), "Name": Name, "Description": Desc, "price": Price }),    
  40.                         dataType: "json",    
  41.                         contentType: "application/json; charset=utf-8",    
  42.                         success: function (result) {    
  43.                             $('#dvLoader').hide();    
  44.     
  45.                             if (result.Status == "True") {    
  46.                                 toastr.success(result.Message);    
  47.                                 clear();    
  48.                                 display();    
  49.                             }    
  50.                             else {    
  51.                                 toastr.success(result.Message);    
  52.                                 clear();    
  53.                                 display();    
  54.     
  55.                             }    
  56.                         }    
  57.                     });    
  58.     
  59.                 }    
  60.     
  61.         });    
  62.     
  63.         $("#btnCancel").click(function () {    
  64.             clear();    
  65.         });    
  66.     
  67.     });   
  68. function clear() {  
  69. $("#txtName").val("");  
  70. $("#txtDesc").val("");  
  71. $("#txtPrice").val("");  
  72. $('#btnSave').val("Save Product");  
  73. $("#hdnPID").val(0);  
  74. }  
  75.    
  76.    
  77. </script>  
Step 11 : Add the Validation in this view for the textbox field. 

Add the style  for creating the red border class
  1. <style>  
  2.     .red_border {  
  3.         border: 1px solid #e46262;  
  4.     }  
  5. </sctipt>  
Add the function of Required field. 
  1. function CheckRequiredFields() {  
  2.            var isValid = true;  
  3.            $('.required').each(function () {  
  4.                if ($.trim($(this).val()) == '') {  
  5.                    isValid = false;  
  6.                    $(this).addClass('red_border');  
  7.   
  8.   
  9.                }  
  10.                else {  
  11.                    $(this).removeClass('red_border');  
  12.   
  13.                }  
  14.            });  
  15.            return isValid;  
  16.        }  
This function is used for required validation like this.

MVC

Step 12 : Add Method in Home Controller for inserting and updating recoreds in the database. 
  1. public JsonResult SaveAndUpdateProduct(int PID,string Name, string Description, float Price)  
  2.       {  
  3.           var result = new jsonMessage();  
  4.           try  
  5.           {  
  6.               //define the model  
  7.               Mst_Product _Mst_Product = new Mst_Product();  
  8.               _Mst_Product.PID = PID;  
  9.               _Mst_Product.Name = Name;  
  10.               _Mst_Product.Description = Description;  
  11.               _Mst_Product.Price = Price;  
  12.   
  13.   
  14.              //for insert recored..  
  15.               if (_Mst_Product.PID == 0)  
  16.               {  
  17.                   context.Mst_Product.Add(_Mst_Product);  
  18.                   result.Message = "your product has been saved success..";  
  19.                   result.Status = true;  
  20.               }  
  21.               else  //for update recored..  
  22.               {  
  23.                   context.Entry(_Mst_Product).State = EntityState.Modified;  
  24.                   result.Message = "your product has been updated successfully..";  
  25.                   result.Status = true;  
  26.               }  
  27.               context.SaveChanges();  
  28.                 
  29.   
  30.           }  
  31.           catch (Exception ex)  
  32.           {  
  33.               ErrorLogers.ErrorLog(ex);  
  34.               result.Message = "We are unable to process your request at this time. Please try again later.";  
  35.               result.Status = false;  
  36.           }  
  37.           return Json(result, JsonRequestBehavior.AllowGet);  
  38.       }  
Step 13: Add the Display record table in this index view and also add the script of this display record.
  1. <div class="col-md-12">  
  2.     <table id="tblProduct" class="table table-striped table-bordered" width="100%">  
  3.         <thead>  
  4.             <tr>  
  5.                
  6.                 <th >Product_ID</th>  
  7.                 <th>Name</th>  
  8.                 <th>Description</th>  
  9.                 <th>Price</th>  
  10.                 <th>Action</th>  
  11.   
  12.             </tr>  
  13.         </thead>  
  14.           
  15.     </table>  
  16. </div>  
Add the script of the display record
  1. function display() {  
  2.            $('#dvLoader').show();  
  3.            Table = $('#tblProduct').DataTable({  
  4.   
  5.                "processing"true,  
  6.                "serverSide"false,  
  7.                "paging"true,  
  8.                "ordering"true,  
  9.                "info"true,  
  10.                "searching"true,  
  11.                "bFilter"false,  
  12.                "scrollX""100%",  
  13.                "scrollY": ($(window).height() - 500),  
  14.                "sScrollXInner""100%",  
  15.                "bScrollCollapse"true,  
  16.                "sAjaxSource"'@Url.Action("GetProduct","Home")',  
  17.                "bDestroy"true,  
  18.                "bLengthChange"true,  
  19.                "bPaginate"true,  
  20.                "sEmptyTable""Loading data from server",  
  21.   
  22.                "columns": [  
  23.                       
  24.                    {  
  25.                        "sWidth""5%",  
  26.                        "sClass""TextCenter PID",  
  27.                        "render": function (data, type, row) {  
  28.                            return row[0];  
  29.                        }  
  30.                    },  
  31.                    { "sWidth""5%""sClass""TextCenter Name""render": function (data, type, row ) { return (row[1]); } },  
  32.                    { "sWidth""5%""sClass""TextCenter Desc""render": function (data, type, row ) { return (row[2]); } },  
  33.                    { "sWidth""5%""sClass""TextCenter Price""render": function (data, type, row ) { return (row[3]); } },  
  34.   
  35.                     {  
  36.                         "bSortable"false,  
  37.                         "sClass""TextCenter",  
  38.                         "sWidth""3%",  
  39.                         "render": function (data, type, row) {  
  40.                             return '<center><a href="javascript:void(0);"  onclick=deleteData("' + row[0] + '"); return false;> <i class="glyphicon glyphicon-trash"></i></a>  <a href="javascript:void(0);"  onclick=EditData(this); return false;> <i class="glyphicon glyphicon-edit"></i></a></center>';  
  41.                         }, "targets": 0,  
  42.                     }  
  43.   
  44.                ],  
  45.                
  46.            });  
  47.            $('#dvLoader').hide();  
  48.        }  
Call this function into the document.ready() function  and also make the second function 
  1. function windowResize() {  
  2.        display();  
  3.         
  4.    };  
  5. $(window).resize(function () {  
  6.            windowResize();  
  7.        });  
Call this  windowResize(); function in to document.ready()
  1. $(document).ready(function () {
    windowResize();
  2. });
Step 14 : Add Method in Home controller  for the Get record and display this record in the Index view. 
  1. public JsonResult GetProduct()  
  2.         {  
  3.   
  4.             List<Mst_Product> _list = new List<Mst_Product>();  
  5.              
  6.             try  
  7.             {  
  8.                 _list = context.Mst_Product.ToList();  
  9.                      var  result = from c in _list  
  10.                          select new[]  
  11.                          {  
  12.                           Convert.ToString( c.PID ),  // 0     
  13.                           Convert.ToString( c.Name ),  // 1     
  14.                           Convert.ToString( c.Description ),  // 2     
  15.                           Convert.ToString( c.Price ),  // 3     
  16.                                                    };  
  17.   
  18.                      return Json(new  
  19.                      {  
  20.                         aaData= result  
  21.                      }, JsonRequestBehavior.AllowGet);  
  22.             }  
  23.   
  24.             catch (Exception ex)  
  25.             {  
  26.                 ErrorLogers.ErrorLog(ex);  
  27.                 return Json(new  
  28.                 {  
  29.                     aaData = new List<string[]> { }  
  30.                 }, JsonRequestBehavior.AllowGet);  
  31.             }  
  32.               
  33.         }  
Step 15 : Add delete and Update function into script tag 
  1. function deleteData(id) {  
  2.     var PID = parseInt(id);  
  3.     bootbox.confirm({  
  4.         title: 'Remove Customer',  
  5.         message: 'Are you sure want to delete this record?',  
  6.         buttons: {  
  7.             'cancel': {  
  8.                 label: 'No',  
  9.                 className: 'btn-default pull-right'  
  10.             },  
  11.             'confirm': {  
  12.                 label: 'Yes',  
  13.                 className: 'btn-primary margin-right-5'  
  14.             }  
  15.         },  
  16.         callback: function(result) {  
  17.             if (result) {  
  18.                 $('#dvLoader').show();  
  19.                 $.ajax({  
  20.                     url: '@Url.Action("DeleteProduct", "Home")',  
  21.                     type: 'POST',  
  22.                     data: JSON.stringify({  
  23.                         "id": id  
  24.                     }),  
  25.                     contentType: 'application/json; charset=utf-8;',  
  26.                     success: function(result) {  
  27.                         windowResize();  
  28.                         $('#dvLoader').hide();  
  29.                         if (result.Status == "True") {  
  30.                             toastr.success(result.Message);  
  31.                             clear();  
  32.                         } else {  
  33.                             toastr.success(result.Message);  
  34.                         }  
  35.                     }  
  36.                 });  
  37.             }  
  38.         }  
  39.     });  
  40. }  
  41.   
  42. function EditData(row)  
  43. {  
  44.     debugger  
  45.     var PID = $(row).closest('tr').find('.PID').html();  
  46.     $("#hdnPID").val(parseInt(PID));  
  47.     var Name = $(row).closest('tr').find('.Name').html();  
  48.     $('#txtName').val(Name);  
  49.     var Desc = $(row).closest('tr').find('.Desc').html();  
  50.     $('#txtDesc').val(Desc);  
  51.     var Price = $(row).closest('tr').find('.Price').html();  
  52.     $('#txtPrice').val(Price);  
  53.     $('#btnSave').val("Update Product");  
  54. }  
Step 17 : Add numeric function because if my texbox is numeric then character value is not allowed.
  1. function isNumberKey(evt) {  
  2.        var charcode = (evt.which) ? evt.which : evt.keycode  
  3.        if (charcode > 31 && (charcode < 48 || charcode > 58)  
  4.            && evt.keyCode != 35 && evt.keyCode != 36 && evt.keyCode != 37  
  5.            && evt.keyCode != 38 && evt.keyCode != 39 && evt.keyCode != 40  
  6.            && evt.keyCode != 46) {  
  7.            return false;  
  8.        }  
  9.        else {  
  10.            return true;  
  11.        }  
  12.    }  
This function is used like this
  1. <input class="form-control required" onkeypress = "return isNumberKey(event)" id="txtPrice" type="text" required />  
Step 18 : Add Method in Home Controller 
  1. public JsonResult DeleteProduct(int id)  
  2.         {  
  3.             var result = new jsonMessage();  
  4.             try  
  5.             {  
  6.   
  7.                 var product = new Mst_Product { PID = id };  
  8.                 context.Entry(product).State = EntityState.Deleted;  
  9.                 context.SaveChanges();  
  10.   
  11.                   
  12.                 result.Message = "your product has been deleted successfully..";  
  13.                 result.Status = true;  
  14.   
  15.             }  
  16.             catch (Exception ex)  
  17.             {  
  18.                 ErrorLogers.ErrorLog(ex);  
  19.                 result.Message = "We are unable to process your request at this time. Please try again later.";  
  20.                 result.Status = false;  
  21.             }  
  22.             return Json(result, JsonRequestBehavior.AllowGet);  
  23.         }  

Now you can perform all the operations on this Project, all files are validated in this project using jquery functions.

MVC

MVC
 
 Summary
 
This article describes how to perform basic CRUD operations in an Asp.Net MVC application using Entity Framework with Ajax call and jquery using Datatable Grid ,Toaster messagebox and also Bootstrap css.