How To Implement Angular Data Table With CRUD Using ASP.NET MVC And Angular

Introduction

In this article, we will discuss how to implement Angular Data Table with (Insert, Update, and Delete) short form (CRUD) using ASP.NET MVC + AngularJS on one page without any full page reloads. This table will be similar to jQuery Data Table and this one is implemented using an Angular data table, an open source plugin that can be downloaded from here. You can find the documentation here.

Background

Recently, I started learning AngularJS using ASP.NET MVC and I started to work with CRUD Operations first. When I searched, I found few articles on Google so I decided to write this article on AngularJS CRUD in MVC. I hope you will like it. 

Steps to create the application

Here, I’m using Database-First approach with Entity Framework in ASP.NET MVC framework.

Step 1

Create one table in SQL database. I have created that with this structure.

ASP.NET

Step 2

  • Create one MVC Web application.
  • Create one Controller class inside the application.
  • Add the database table model in the application using Entity Framework.
  • Download or install the required files to create Angular Data Tables from NuGet Package Manager or from CDN.
    1. Install-Package angularjs -Version 1.6.6
    2. Install-Package jquery.datatables -Version 1.10.15
    3. Install-Package bootstrap -Version 4.0.0-beta

As it runs with jQuery, install the jQuery also in your application. We are using Bootstrap Modal Popup to insert and update.

Step 3 - Implementation

Defining Index View

Refer to the JavaScript files and other CSS files in the master page.

Create one action method in Controller class to get all the records from table and display in grid format. Just add the following code.

  1. public ActionResult GetData()  
  2.         {  
  3.             using (DemoEntities db = new DemoEntities())  
  4.             {  
  5.                 var result = db.Employees.ToList();  
  6.                 return new JsonResult { Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
  7.             }  
  8.         }  

We have written a method to retrieve the data from DB and show in Grid. Now, we have to create one JS file in Scripts folder to define AngularJS Controllers and other scripts inside it.

  1. var app = angular.module('MyApp', [‘datatables’]);  
  2. app. controller("BindAngularDirectiveEmpCtrl", BindAngularDirectiveEmpCtrl)  
  3. function BindAngularDirectiveEmpCtrl($scope, $filter, $timeout, $compile,      DTOptionsBuilder, DTColumnDefBuilder, DTColumnBuilder)  
  4. {  
  5.   var vm = this;  
  6.   vm.Employees = {};  
  7. vm.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', { // call GetData method  
  8.         url: "/Employee/GetData",  
  9.         type: "POST"  
  10.     })  
  11. .withPaginationType('full_numbers')  
  12.     .withOption('createdRow', createdRow);  
  13.   
  14. function createdRow(row, data, dataIndex) {  
  15.         // Recompiling so we can bind Angular directive to the DT  
  16.         $compile(angular.element(row).contents())($scope);  
  17.     }  
  18. }  

Now, create a Column builder in order to show the data in Angular Data Table. For that, add the below code (you can define your own column names in it).

  1. vm.dtColumns = [  
  2.         DTColumnBuilder.newColumn('EmployeeID').withTitle('EmployeeID'),  
  3.         DTColumnBuilder.newColumn('EmpNo').withTitle('EmpNo'),  
  4.          DTColumnBuilder.newColumn('FirstName').withTitle('FirstName'),  
  5.           DTColumnBuilder.newColumn('LastName').withTitle('LastName'),  
  6.            DTColumnBuilder.newColumn('Gender').withTitle('Gender'),  
  7.             DTColumnBuilder.newColumn('DOB').withTitle('DOB').withClass('text-danger').withOption('width','60px%').renderWith(function (data, type) {  
  8.                 // return formatJSONDate(data);  
  9.                 return $filter('mydate')(data, 'dd/MM/yyyy'); //date filter  
  10.   
  11.             }),  
  12.              //DTColumnBuilder.newColumn('DOB').withTitle('DOB').renderWith(FotmatDateTime),  
  13.              DTColumnBuilder.newColumn('MartialStatus').withTitle('MartialStatus'),  
  14.           DTColumnBuilder.newColumn('Address').withTitle('Address'),  
  15.           DTColumnBuilder.newColumn('Mobile').withTitle('Mobile'),  
  16.     DTColumnBuilder.newColumn('Email').withTitle('Email'),  
  17.     DTColumnBuilder.newColumn('PhotoPath').withTitle('PhotoPath'),  
  18.     DTColumnBuilder.newColumn('Status').withTitle('Status'),  
  19. ];  

Create View to show Index

Add the following HTML markup to show the data in the table and run the application. You will see the data in the table with searching and paging.

  1. <div ng-app ="MyApp">   
  2.    <div ng-controller="BindAngularDirectiveCtrl as showCase">   
  3.    <table datatable="" dt-options="showCase.dtOptions" dt-columns="showCase.dtColumns" dt-instance="showCase.dtInstance" class="row-border hover"></table> </div>  
  4. </div>  


Figure - 
Angular Data Table with searching and pagination

CRUD Actions

To create CRUD operations (i.e. Insert, Update, Delete) actions to table, add the following code to the JS file.

  1. DTColumnBuilder.newColumn(null).withTitle('Actions').notSortable() .renderWith(actionsHtml)  
  2. function actionsHtml(data, type, full, meta) {  
  3.         vm.Employees[data.EmployeeID] = data;  
  4.         return '<a   title="Edit"  href="javascript:void(0)" >' +  
  5.             '   <i class="fa fa fa-pencil"></i>' +  
  6.             '</a> ' +  
  7.             '<a   title="Delete" href="javascript:void(0)" >' +  
  8.             '   <i class="fa fa-trash-o"></i>' +  
  9.             '</a>';  
  10.     }  

Save the code and run it. You will receive the output like this.

ASP.NET
Figure -
 Actions

Edit Employee

Create functions in JS file in order to edit/update. To do that, create one method in ASP.NET MVC. If we pass the id from View to code behind, then it will retrieve the record of that ID and it will pass the result to the Bootstrap Modal Popup.

  1. public ActionResult EditEmp(int id)  
  2.         {  
  3.             using (DemoEntities db = new DemoEntities())  
  4.             {  
  5.                 var result = db.Employees.Where(x => x.EmployeeID.Equals(id)).FirstOrDefault();  
  6.                 return new JsonResult { Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
  7.             }  
  8.         }  

To call the method using Angular.js, write the following code.

  1. vm.edit = edit;  
  2. function edit(person) {   
  3. // Edit some data and call server to make changes...  
  4. // Then reload the data so that DT is refreshed  
  5.  vm.dtInstance.reloadData();   
  6. }  
  7. function actionsHtml(data, type, full, meta) {  
  8.         vm.Employees[data.EmployeeID] = data;  
  9.         return '<a   title="Edit"  href="javascript:void(0)" ng-click="showCase.edit(showCase.Employees[' + data.EmployeeID + '])">' +  
  10.             '   <i class="fa fa fa-pencil"></i>' +  
  11.             '</a> ' +              
  12.     }  

Create one modal popup to show the edited values in View. It will look like the below code and add ng-model properties in order to access the AngularJS Controllers.

  1. <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">  
  2.          <div class="modal-dialog">  
  3.              <div class="modal-content">  
  4.                  <div class="modal-header">  
  5.                      <button type="button" class="close" data-dismiss="modal">×</button>  
  6.                      <h4 class="modal-title" id="myModalLabel">{{EmpHeading}}</h4>  
  7.                  </div>  
  8.                  <div class="modal-body">  
  9.                      <form>  
  10.                          <div class="form-group">  
  11.                              <label for="EmployeeId">EmployeeID</label>  
  12.                              <input type="text" class="form-control" id="txtEmployeeID" ng-model="EmployeeID" placeholder="EmployeeId" disabled="disabled" />  
  13.                          </div>  
  14.                          <div class="form-group">  
  15.                              <label for="EmpNo">EmpNo</label>  
  16.                              <input type="text" class="form-control" ng-model="EmpNo" id="txtEmpNo" placeholder="EmpNo" />  
  17.                          </div>  
  18.                          <div class="form-group">  
  19.                              <label for="txtFirstName">FirstName</label>  
  20.                              <input type="text" class="form-control" ng-model="FirstName" id="txtFirstName" placeholder="FirstName" />  
  21.                          </div>  
  22.                          <div class="form-group">  
  23.                              <label for="txtLastName">LastName</label>  
  24.                              <input type="text" class="form-control" ng-model="LastName" id="txtLastName" placeholder="LastName" />  
  25.                          </div>  
  26.                          <div class="form-group">  
  27.                              <label for="txtGender">Gender</label>  
  28.                              <select ng-model="Gender" class="form-control" id="ddlGender">  
  29.                                  <option value="">Select</option>  
  30.                                  <option value="0">Male</option>  
  31.                                  <option value="1">Female</option>  
  32.                              </select>  
  33.                          </div>  
  34.                          <div class="form-group">  
  35.                              <label for="txtDOB">DOB</label>  
  36.                              <input type="text" ng-model="DOB" data-date-time-picker class="form-control" id="txtDOB" placeholder="DOB" />  
  37.                          </div>  
  38.                          <div class="form-group">  
  39.                              <label for="txtMartialStatus">MartialStatus</label>  
  40.                              <input type="text" class="form-control" ng-model="MartialStatus" id="txtMartialStatus" placeholder="MartialStatus" />  
  41.                          </div>  
  42.                          <div class="form-group">  
  43.                              <label for="txtAddress">Address</label>  
  44.                              <input type="text" class="form-control" ng-model="Address" id="txtAddress" placeholder="Address" />  
  45.                          </div>  
  46.                          <div class="form-group">  
  47.                              <label for="txtMobile">Mobile</label>  
  48.                              <input type="text" class="form-control" ng-model="Mobile" id="txtMobile" placeholder="Mobile" />  
  49.                          </div>  
  50.   
  51.                          <div class="form-group">  
  52.                              <label for="txtEmail">Email</label>  
  53.                              <input type="text" class="form-control" ng-model="Email" id="txtEmail" placeholder="Email" />  
  54.                          </div>  
  55.                          <div class="form-group">  
  56.                              <label for="txtPhotoPath">PhotoPath</label>  
  57.                              <input type="text" class="form-control" id="txtPhotoPath" ng-model="PhotoPath" placeholder="PhotoPath" />  
  58.                          </div>  
  59.                          <div class="form-group">  
  60.                              <label for="ddlStatus">Status</label>  
  61.                              <select id="ddlStatus" ng-model="Status" class="form-control">  
  62.                                  <option value="">Select</option>  
  63.                                  <option value="1">true</option>  
  64.                                  <option value="0">false</option>  
  65.                              </select>  
  66.                          </div>  
  67.                      </form>  
  68.                  </div>  
  69.                  <div class="modal-footer">  
  70.                      <button type="button" class="btn btn-primary" id="btnAdd" ng-if="btnAdd" ng-click="showCase.AddNewEmp()">Add</button>  
  71.                      <button type="button" class="btn btn-primary" id="btnUpdate" ng-if="btnUpDate" ng-click="showCase.Update()">Update</button>  
  72.                      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>  
  73.                  </div>  
  74.              </div>  
  75.          </div>  
  76.      </div>  

Create one Angular Service to call the server side method as it is similar to AJAX call in jQuery.

  1. app.service("EmpCrudservice"function ($http) {  
  2. //get emp byid  
  3.     this.EditById = function (empid) {  
  4.         var response = $http({  
  5.             method: "post",  
  6.             url: '/Employee/EditEmp',  
  7.             params: {  
  8.                 id: JSON.stringify(empid)  
  9.             }  
  10.         });  
  11.         return response;  
  12.     }  
  13. }  

Now, refer this service to JS file Controller in order to access the methods inside it and write the following code inside "Edit" function. This function will be called when Edit link is clicked in Data Table.

Here, we are passing the employee id from the data table. This method uses HTTP service and returns the data of the employee to show it in Bootstrap Modal.
  1. function edit(emp) {  
  2.       //vm.message = 'You are trying to edit the row: ' + JSON.stringify(emp);  
  3.       // Edit some data and call server to make changes...  
  4.       var ddlgender = angular.element(document.getElementById("ddlGender"));  
  5.       var stsddl = angular.element(document.getElementById("ddlStatus"));  
  6.       var modalpopup = angular.element(document.getElementById("myModal"));  
  7.       //  var btnupdate = angular.element(document.getElementById("btnUpdate"));  
  8.       var btnAdd = angular.element(document.getElementById("btnAdd"));  
  9.       $scope.EmpHeading = "Edit Employee";  
  10.       var response = EmpCrudservice.EditById(emp.EmployeeID);  
  11.       response.then(function (d) {  
  12.           console.log(d.data);  
  13.           $scope.emp = d.data;  
  14.           $scope.EmployeeID = emp.EmployeeID;  
  15.           $scope.EmpNo = emp.EmpNo;  
  16.           $scope.FirstName = emp.FirstName;  
  17.           $scope.LastName = emp.LastName;  
  18.           // $scope.Gender = emp.Gender;  
  19.   
  20.           if (emp.Gender == "Male") {  
  21.               ddlgender.val("0");  
  22.           }  
  23.           else if (emp.Gender == "Female") {  
  24.               ddlgender.val("1");  
  25.           }  
  26.           $scope.DOB = formatJSONDate(emp.DOB);  
  27.           $scope.MartialStatus = emp.MartialStatus;  
  28.           $scope.Address = emp.Address;  
  29.           $scope.Mobile = emp.Mobile;  
  30.           $scope.Email = emp.Email;  
  31.           $scope.PhotoPath = emp.PhotoPath;  
  32.           //$scope.Status = emp.Status;  
  33.   
  34.           if (emp.Status == true) {  
  35.               stsddl.val("1");  
  36.   
  37.           }  
  38.           else if (emp.Status == false) {  
  39.               stsddl.val("0");  
  40.   
  41.           }  
  42.           modalpopup.modal('show');  
  43.           $scope.btnUpDate = true//showing update button after edit button click  
  44.           $scope.btnAdd = false;  
  45.           //   btnupdate.show();  
  46.           //btnAdd.hide(); //this code i edited  
  47.   
  48.   
  49.       }, function (e) {  
  50.           console.log(e.data);  
  51.           alert("error in editing data");  
  52.   
  53.       });  
  54.   
  55.       // Then reload the data so that DT is refreshed  
  56.       vm.dtInstance.reloadData();  
  57.   }  

Now, if we run it, we can see when we click on the "Edit employee", it will make an HTTP request and get the corresponding data from DB. Then, it displays that in the Bootstrap Modal. Now, we have to edit the data in the modal form and we should update it to the DB in order to do that.

Update Employee

Create one update service in AngularJS file to perform some update operation to that edited record when update button is clicked.  

  1. //update emp  
  2.   
  3. this.UpdateEmp = function (emp) {  
  4.     var response = $http({  
  5.         method: "post",  
  6.         url: '/Employee/Update',  
  7.         data: JSON.stringify(emp),  
  8.         datatype: 'json'  
  9.     });  
  10.     return response;  
  11. }  

And also, create one server method to fire the update operation in DB.

  1. public ActionResult Update(Employee e)  
  2.       {  
  3.           if (e.EmployeeID > 0)  
  4.           {  
  5.               using (DemoEntities db = new DemoEntities())  
  6.               {  
  7.   
  8.                   var emp = db.Employees.Where(x => x.EmployeeID.Equals(e.EmployeeID)).FirstOrDefault();  
  9.                   if (emp != null)  
  10.                   {  
  11.                       emp.EmpNo = e.EmpNo;  
  12.                       emp.FirstName = e.FirstName;  
  13.                       emp.LastName = e.LastName;  
  14.                       emp.Gender = e.Gender;  
  15.                       emp.MartialStatus = e.MartialStatus;  
  16.                       emp.Mobile = e.Mobile;  
  17.                       emp.Email = e.Email;  
  18.                       emp.DOB = e.DOB;  
  19.                       emp.Address = e.Address;  
  20.                       emp.Status = e.Status;  
  21.                       emp.PhotoPath = e.PhotoPath;  
  22.                   }  
  23.                   db.SaveChanges();  
  24.               }  
  25.           }  
  26.           return new JsonResult { Data = "Updated successfully", JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
  27.       }  

Now, create one update function in JS Controller file to do update on update link button.

  1. vm.Update = update;  
  2.   //update emp  
  3.   
  4. function update() {  
  5.         var ddlgender = angular.element(document.getElementById("ddlGender"));  
  6.         var ddlstatus = angular.element(document.getElementById("ddlStatus"));  
  7.         var modalpopup = angular.element(document.getElementById("myModal"));  
  8.   
  9.         var empObj = {  
  10.             EmployeeID: $scope.EmployeeID,  
  11.             EmpNo: $scope.EmpNo,  
  12.             FirstName: $scope.FirstName,  
  13.             LastName: $scope.LastName,  
  14.             Gender: ddlgender.val() == "0" ? "Male" : "Female",  
  15.             DOB: $scope.DOB,  
  16.             MartialStatus: $scope.MartialStatus,  
  17.             Address: $scope.Address,  
  18.             Mobile: $scope.Mobile,  
  19.             Email: $scope.Email,  
  20.             PhotoPath: $scope.PhotoPath,  
  21.             Status: ddlstatus.val() == "1" ? "true" : "false"  
  22.         }  
  23.         console.log(empObj);  
  24.         var response = EmpCrudservice.UpdateEmp(empObj);  
  25.         response.then(function (d) {  
  26.             alert(d.data);  
  27.             modalpopup.modal('hide');  
  28.             // Then reload the data so that DT is refreshed  
  29.             vm.dtInstance.reloadData();  
  30.   
  31.         }, function (err) {  
  32.             console.log("err in updating");  
  33.             console.log(err.data);  
  34.         })  
  35.     }  

Delete Employee

In order to delete the employee from DB, we need to pass the id of the record. In order to do that, create an action method in Controller.

  1. public ActionResult Delete(int id)  
  2.         {  
  3.             using (DemoEntities db = new DemoEntities())  
  4.             {  
  5.                 var result = db.Employees.Where(x => x.EmployeeID.Equals(id)).FirstOrDefault();  
  6.                 if (result != null)  
  7.                 {  
  8.                     db.Employees.Remove(result);  
  9.                     db.SaveChanges();  
  10.                 }  
  11.             }  
  12.             return new JsonResult { Data = "Delted Employee", JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
  13.         }  

And, we have to define the HTML for "Delete" link, so create one anchor tag in JS file so that when we click on the link of the particular record column by taking ID as reference, the record will be deleted.

  1. '<a   title="Delete" href="javascript:void(0)" ng-click="showCase.delete(showCase.Employees[' + data.EmployeeID + '])" )"="">' +  
  2.             '   <i class="fa fa-trash-o"></i>' +  
  3.             '</a>'  

Create a function in Angular Service to call the server side method.

  1. //Delete emp  
  2.     this.DelteById = function (id) {  
  3.         var response = $http({  
  4.             method: "post",  
  5.             url: '/Employee/Delete',  
  6.             params: {  
  7.                 id: JSON.stringify(id)  
  8.             }  
  9.         });  
  10.         return response;  
  11.     }  

Refer to the service method in Controller and the delete functionality will be finished.

  1. vm.delete = deleteRow;  
  2. function deleteRow(emp) {  
  3.         // Delete some data and call server to make changes...  
  4.         var request = confirm("Are you sure want to delete this id:" + emp.EmployeeID);  
  5.         if (request) {  
  6.             var response = EmpCrudservice.DelteById(emp.EmployeeID);  
  7.             response.then(function (d) {  
  8.                 var result = d.data;  
  9.                 alert(result);  
  10.                 // Then reload the data so that DT is refreshed  
  11.                 vm.dtInstance.reloadData();  
  12.   
  13.             }, function (err) {  
  14.                 alert("error in deleting emp");  
  15.                 console.log(err.data);  
  16.             });  
  17.         }  
  18.   
  19.     }  

Add Employee

As we have already created the bootstrap modal for Addition, just create one button for calling the modal popup when add button is clicked.

  1. <button type="button" class="btn btn-success" ng-click="showCase.OpenAddPopup()">Add Employee</button>  

Create one method in Angular Controller to call the Modal popup from View. When opening the popup, we need to clear the previous values from the form. So, create one method to empty the modal object in AngularJS.

  1. vm.OpenAddPopup = AddEmpPopup;  
  2. //open modal popup Emp  
  3.     function AddEmpPopup() {  
  4.         ClearFields();  
  5.         var modalpopup = angular.element(document.getElementById("myModal"));  
  6.         modalpopup.modal('show');  
  7.         $scope.EmpHeading = "Add Employee";  
  8.   
  9.     }  
  10. //clearing all fields  
  11.     function ClearFields() {  
  12.         var ddlgender = angular.element(document.getElementById("ddlGender"));  
  13.         var ddlstatus = angular.element(document.getElementById("ddlStatus"));  
  14.         $scope.EmployeeID = "";  
  15.         $scope.EmpNo = "";  
  16.         $scope.FirstName = "";  
  17.         $scope.LastName = "";  
  18.         ddlgender.val("");  
  19.         $scope.DOB = "";  
  20.         $scope.MartialStatus = "";  
  21.         $scope.Address = "";  
  22.         $scope.Mobile = "";  
  23.         $scope.Email = "";  
  24.         $scope.PhotoPath = "";  
  25.         ddlstatus.val("");  
  26.   
  27.         $scope.btnUpDate = false;  
  28.         $scope.btnAdd = true;  
  29.     }  

Here, I have added $scope.btnUpdate to visible and $scope.btnAdd to show and hide in Bootstrap modal popup. So, at the starting of Controller in AngularJS, set default values of $scope variables and on clearing the values of scope object, I’m setting the values of scope variables as shown above.

  1. //used for hiding and showing edit and buttons  
  2.     $scope.btnUpDate = false;  
  3.     $scope.btnAdd = false;  

After showing the Bootstrap Modal, we need to fill the details in the form and we should pass the form data to DB on "ADD" button click. So, add one function in Controller in JS file to call the Angular Service to fire Server-side code.

  1. //add Employee  
  2.     this.AddEmp = function (emp) {  
  3.         var response = $http({  
  4.             method: "post",  
  5.             url: '/Employee/AddEmployee',  
  6.             data: JSON.stringify(emp),  
  7.             datatype: 'json'  
  8.         });  
  9.         return response;  
  10.     }  

Call this method in function to add.

  1. //add emp when pop up opens  
  2.     function AddEmp() {  
  3.         var ddlgender = angular.element(document.getElementById("ddlGender"));  
  4.         var ddlstatus = angular.element(document.getElementById("ddlStatus"));  
  5.         var modalpopup = angular.element(document.getElementById("myModal"));  
  6.         var empObj = {  
  7.             EmployeeID: $scope.EmployeeID,  
  8.             EmpNo: $scope.EmpNo,  
  9.             FirstName: $scope.FirstName,  
  10.             LastName: $scope.LastName,  
  11.             Gender: ddlgender.val() == "0" ? "Male" : "Female",  
  12.             DOB: $scope.DOB,  
  13.             MartialStatus: $scope.MartialStatus,  
  14.             Address: $scope.Address,  
  15.             Mobile: $scope.Mobile,  
  16.             Email: $scope.Email,  
  17.             PhotoPath: $scope.PhotoPath,  
  18.             Status: ddlstatus.val() == "1" ? "true" : "false"  
  19.         }  
  20.         console.log(empObj);  
  21.         var response = EmpCrudservice.AddEmp(empObj); //calling angular service  
  22.         response.then(function (d) {  
  23.             alert(d.data);  
  24.             modalpopup.modal('hide');  
  25.             vm.dtInstance.reloadData();  
  26.   
  27.         }, function (err) {  
  28.             console.log("error in adding employee");  
  29.             console.log(err.data);  
  30.         });  
  31.   
  32.     }  

Server side method to add Employee.

  1. public JsonResult AddEmployee(Employee e)  
  2.     {  
  3.         using (DemoEntities db = new DemoEntities())  
  4.         {  
  5.             db.Employees.Add(e);  
  6.             db.SaveChanges();  
  7.   
  8.         }  
  9.         return new JsonResult { Data = "Added Employee", JsonRequestBehavior = JsonRequestBehavior.AllowGet };  
  10.     }  

Save it and run it. You will see the final output.


Adding an employee

ASP.NET 

Editing and Updating Employee