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.
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.
- Install-Package angularjs -Version 1.6.6
- Install-Package jquery.datatables -Version 1.10.15
- 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.
- public ActionResult GetData()
- {
- using (DemoEntities db = new DemoEntities())
- {
- var result = db.Employees.ToList();
- return new JsonResult { Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
- }
- }
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.
- var app = angular.module('MyApp', [‘datatables’]);
- app. controller("BindAngularDirectiveEmpCtrl", BindAngularDirectiveEmpCtrl)
- function BindAngularDirectiveEmpCtrl($scope, $filter, $timeout, $compile, DTOptionsBuilder, DTColumnDefBuilder, DTColumnBuilder)
- {
- var vm = this;
- vm.Employees = {};
- vm.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
- url: "/Employee/GetData",
- type: "POST"
- })
- .withPaginationType('full_numbers')
- .withOption('createdRow', createdRow);
-
- function createdRow(row, data, dataIndex) {
-
- $compile(angular.element(row).contents())($scope);
- }
- }
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).
- vm.dtColumns = [
- DTColumnBuilder.newColumn('EmployeeID').withTitle('EmployeeID'),
- DTColumnBuilder.newColumn('EmpNo').withTitle('EmpNo'),
- DTColumnBuilder.newColumn('FirstName').withTitle('FirstName'),
- DTColumnBuilder.newColumn('LastName').withTitle('LastName'),
- DTColumnBuilder.newColumn('Gender').withTitle('Gender'),
- DTColumnBuilder.newColumn('DOB').withTitle('DOB').withClass('text-danger').withOption('width','60px%').renderWith(function (data, type) {
-
- return $filter('mydate')(data, 'dd/MM/yyyy');
-
- }),
-
- DTColumnBuilder.newColumn('MartialStatus').withTitle('MartialStatus'),
- DTColumnBuilder.newColumn('Address').withTitle('Address'),
- DTColumnBuilder.newColumn('Mobile').withTitle('Mobile'),
- DTColumnBuilder.newColumn('Email').withTitle('Email'),
- DTColumnBuilder.newColumn('PhotoPath').withTitle('PhotoPath'),
- DTColumnBuilder.newColumn('Status').withTitle('Status'),
- ];
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.
- <div ng-app ="MyApp">
- <div ng-controller="BindAngularDirectiveCtrl as showCase">
- <table datatable="" dt-options="showCase.dtOptions" dt-columns="showCase.dtColumns" dt-instance="showCase.dtInstance" class="row-border hover"></table> </div>
- </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.
- DTColumnBuilder.newColumn(null).withTitle('Actions').notSortable() .renderWith(actionsHtml)
- function actionsHtml(data, type, full, meta) {
- vm.Employees[data.EmployeeID] = data;
- return '<a title="Edit" href="javascript:void(0)" >' +
- ' <i class="fa fa fa-pencil"></i>' +
- '</a> ' +
- '<a title="Delete" href="javascript:void(0)" >' +
- ' <i class="fa fa-trash-o"></i>' +
- '</a>';
- }
Save the code and run it. You will receive the output like this.
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.
- public ActionResult EditEmp(int id)
- {
- using (DemoEntities db = new DemoEntities())
- {
- var result = db.Employees.Where(x => x.EmployeeID.Equals(id)).FirstOrDefault();
- return new JsonResult { Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
- }
- }
To call the method using Angular.js, write the following code.
- vm.edit = edit;
- function edit(person) {
-
-
- vm.dtInstance.reloadData();
- }
- function actionsHtml(data, type, full, meta) {
- vm.Employees[data.EmployeeID] = data;
- return '<a title="Edit" href="javascript:void(0)" ng-click="showCase.edit(showCase.Employees[' + data.EmployeeID + '])">' +
- ' <i class="fa fa fa-pencil"></i>' +
- '</a> ' +
- }
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.
- <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <button type="button" class="close" data-dismiss="modal">×</button>
- <h4 class="modal-title" id="myModalLabel">{{EmpHeading}}</h4>
- </div>
- <div class="modal-body">
- <form>
- <div class="form-group">
- <label for="EmployeeId">EmployeeID</label>
- <input type="text" class="form-control" id="txtEmployeeID" ng-model="EmployeeID" placeholder="EmployeeId" disabled="disabled" />
- </div>
- <div class="form-group">
- <label for="EmpNo">EmpNo</label>
- <input type="text" class="form-control" ng-model="EmpNo" id="txtEmpNo" placeholder="EmpNo" />
- </div>
- <div class="form-group">
- <label for="txtFirstName">FirstName</label>
- <input type="text" class="form-control" ng-model="FirstName" id="txtFirstName" placeholder="FirstName" />
- </div>
- <div class="form-group">
- <label for="txtLastName">LastName</label>
- <input type="text" class="form-control" ng-model="LastName" id="txtLastName" placeholder="LastName" />
- </div>
- <div class="form-group">
- <label for="txtGender">Gender</label>
- <select ng-model="Gender" class="form-control" id="ddlGender">
- <option value="">Select</option>
- <option value="0">Male</option>
- <option value="1">Female</option>
- </select>
- </div>
- <div class="form-group">
- <label for="txtDOB">DOB</label>
- <input type="text" ng-model="DOB" data-date-time-picker class="form-control" id="txtDOB" placeholder="DOB" />
- </div>
- <div class="form-group">
- <label for="txtMartialStatus">MartialStatus</label>
- <input type="text" class="form-control" ng-model="MartialStatus" id="txtMartialStatus" placeholder="MartialStatus" />
- </div>
- <div class="form-group">
- <label for="txtAddress">Address</label>
- <input type="text" class="form-control" ng-model="Address" id="txtAddress" placeholder="Address" />
- </div>
- <div class="form-group">
- <label for="txtMobile">Mobile</label>
- <input type="text" class="form-control" ng-model="Mobile" id="txtMobile" placeholder="Mobile" />
- </div>
-
- <div class="form-group">
- <label for="txtEmail">Email</label>
- <input type="text" class="form-control" ng-model="Email" id="txtEmail" placeholder="Email" />
- </div>
- <div class="form-group">
- <label for="txtPhotoPath">PhotoPath</label>
- <input type="text" class="form-control" id="txtPhotoPath" ng-model="PhotoPath" placeholder="PhotoPath" />
- </div>
- <div class="form-group">
- <label for="ddlStatus">Status</label>
- <select id="ddlStatus" ng-model="Status" class="form-control">
- <option value="">Select</option>
- <option value="1">true</option>
- <option value="0">false</option>
- </select>
- </div>
- </form>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-primary" id="btnAdd" ng-if="btnAdd" ng-click="showCase.AddNewEmp()">Add</button>
- <button type="button" class="btn btn-primary" id="btnUpdate" ng-if="btnUpDate" ng-click="showCase.Update()">Update</button>
- <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
- </div>
- </div>
- </div>
- </div>
Create one Angular Service to call the server side method as it is similar to AJAX call in jQuery.
- app.service("EmpCrudservice", function ($http) {
-
- this.EditById = function (empid) {
- var response = $http({
- method: "post",
- url: '/Employee/EditEmp',
- params: {
- id: JSON.stringify(empid)
- }
- });
- return response;
- }
- }
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.
- function edit(emp) {
-
-
- var ddlgender = angular.element(document.getElementById("ddlGender"));
- var stsddl = angular.element(document.getElementById("ddlStatus"));
- var modalpopup = angular.element(document.getElementById("myModal"));
-
- var btnAdd = angular.element(document.getElementById("btnAdd"));
- $scope.EmpHeading = "Edit Employee";
- var response = EmpCrudservice.EditById(emp.EmployeeID);
- response.then(function (d) {
- console.log(d.data);
- $scope.emp = d.data;
- $scope.EmployeeID = emp.EmployeeID;
- $scope.EmpNo = emp.EmpNo;
- $scope.FirstName = emp.FirstName;
- $scope.LastName = emp.LastName;
-
-
- if (emp.Gender == "Male") {
- ddlgender.val("0");
- }
- else if (emp.Gender == "Female") {
- ddlgender.val("1");
- }
- $scope.DOB = formatJSONDate(emp.DOB);
- $scope.MartialStatus = emp.MartialStatus;
- $scope.Address = emp.Address;
- $scope.Mobile = emp.Mobile;
- $scope.Email = emp.Email;
- $scope.PhotoPath = emp.PhotoPath;
-
-
- if (emp.Status == true) {
- stsddl.val("1");
-
- }
- else if (emp.Status == false) {
- stsddl.val("0");
-
- }
- modalpopup.modal('show');
- $scope.btnUpDate = true;
- $scope.btnAdd = false;
-
-
-
-
- }, function (e) {
- console.log(e.data);
- alert("error in editing data");
-
- });
-
-
- vm.dtInstance.reloadData();
- }
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.
-
-
- this.UpdateEmp = function (emp) {
- var response = $http({
- method: "post",
- url: '/Employee/Update',
- data: JSON.stringify(emp),
- datatype: 'json'
- });
- return response;
- }
And also, create one server method to fire the update operation in DB.
- public ActionResult Update(Employee e)
- {
- if (e.EmployeeID > 0)
- {
- using (DemoEntities db = new DemoEntities())
- {
-
- var emp = db.Employees.Where(x => x.EmployeeID.Equals(e.EmployeeID)).FirstOrDefault();
- if (emp != null)
- {
- emp.EmpNo = e.EmpNo;
- emp.FirstName = e.FirstName;
- emp.LastName = e.LastName;
- emp.Gender = e.Gender;
- emp.MartialStatus = e.MartialStatus;
- emp.Mobile = e.Mobile;
- emp.Email = e.Email;
- emp.DOB = e.DOB;
- emp.Address = e.Address;
- emp.Status = e.Status;
- emp.PhotoPath = e.PhotoPath;
- }
- db.SaveChanges();
- }
- }
- return new JsonResult { Data = "Updated successfully", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
- }
Now, create one update function in JS Controller file to do update on update link button.
- vm.Update = update;
-
-
- function update() {
- var ddlgender = angular.element(document.getElementById("ddlGender"));
- var ddlstatus = angular.element(document.getElementById("ddlStatus"));
- var modalpopup = angular.element(document.getElementById("myModal"));
-
- var empObj = {
- EmployeeID: $scope.EmployeeID,
- EmpNo: $scope.EmpNo,
- FirstName: $scope.FirstName,
- LastName: $scope.LastName,
- Gender: ddlgender.val() == "0" ? "Male" : "Female",
- DOB: $scope.DOB,
- MartialStatus: $scope.MartialStatus,
- Address: $scope.Address,
- Mobile: $scope.Mobile,
- Email: $scope.Email,
- PhotoPath: $scope.PhotoPath,
- Status: ddlstatus.val() == "1" ? "true" : "false"
- }
- console.log(empObj);
- var response = EmpCrudservice.UpdateEmp(empObj);
- response.then(function (d) {
- alert(d.data);
- modalpopup.modal('hide');
-
- vm.dtInstance.reloadData();
-
- }, function (err) {
- console.log("err in updating");
- console.log(err.data);
- })
- }
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.
- public ActionResult Delete(int id)
- {
- using (DemoEntities db = new DemoEntities())
- {
- var result = db.Employees.Where(x => x.EmployeeID.Equals(id)).FirstOrDefault();
- if (result != null)
- {
- db.Employees.Remove(result);
- db.SaveChanges();
- }
- }
- return new JsonResult { Data = "Delted Employee", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
- }
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.
- '<a title="Delete" href="javascript:void(0)" ng-click="showCase.delete(showCase.Employees[' + data.EmployeeID + '])" )"="">' +
- ' <i class="fa fa-trash-o"></i>' +
- '</a>'
Create a function in Angular Service to call the server side method.
-
- this.DelteById = function (id) {
- var response = $http({
- method: "post",
- url: '/Employee/Delete',
- params: {
- id: JSON.stringify(id)
- }
- });
- return response;
- }
Refer to the service method in Controller and the delete functionality will be finished.
- vm.delete = deleteRow;
- function deleteRow(emp) {
-
- var request = confirm("Are you sure want to delete this id:" + emp.EmployeeID);
- if (request) {
- var response = EmpCrudservice.DelteById(emp.EmployeeID);
- response.then(function (d) {
- var result = d.data;
- alert(result);
-
- vm.dtInstance.reloadData();
-
- }, function (err) {
- alert("error in deleting emp");
- console.log(err.data);
- });
- }
-
- }
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.
- <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.
- vm.OpenAddPopup = AddEmpPopup;
-
- function AddEmpPopup() {
- ClearFields();
- var modalpopup = angular.element(document.getElementById("myModal"));
- modalpopup.modal('show');
- $scope.EmpHeading = "Add Employee";
-
- }
-
- function ClearFields() {
- var ddlgender = angular.element(document.getElementById("ddlGender"));
- var ddlstatus = angular.element(document.getElementById("ddlStatus"));
- $scope.EmployeeID = "";
- $scope.EmpNo = "";
- $scope.FirstName = "";
- $scope.LastName = "";
- ddlgender.val("");
- $scope.DOB = "";
- $scope.MartialStatus = "";
- $scope.Address = "";
- $scope.Mobile = "";
- $scope.Email = "";
- $scope.PhotoPath = "";
- ddlstatus.val("");
-
- $scope.btnUpDate = false;
- $scope.btnAdd = true;
- }
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.
-
- $scope.btnUpDate = false;
- $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.
-
- this.AddEmp = function (emp) {
- var response = $http({
- method: "post",
- url: '/Employee/AddEmployee',
- data: JSON.stringify(emp),
- datatype: 'json'
- });
- return response;
- }
Call this method in function to add.
-
- function AddEmp() {
- var ddlgender = angular.element(document.getElementById("ddlGender"));
- var ddlstatus = angular.element(document.getElementById("ddlStatus"));
- var modalpopup = angular.element(document.getElementById("myModal"));
- var empObj = {
- EmployeeID: $scope.EmployeeID,
- EmpNo: $scope.EmpNo,
- FirstName: $scope.FirstName,
- LastName: $scope.LastName,
- Gender: ddlgender.val() == "0" ? "Male" : "Female",
- DOB: $scope.DOB,
- MartialStatus: $scope.MartialStatus,
- Address: $scope.Address,
- Mobile: $scope.Mobile,
- Email: $scope.Email,
- PhotoPath: $scope.PhotoPath,
- Status: ddlstatus.val() == "1" ? "true" : "false"
- }
- console.log(empObj);
- var response = EmpCrudservice.AddEmp(empObj);
- response.then(function (d) {
- alert(d.data);
- modalpopup.modal('hide');
- vm.dtInstance.reloadData();
-
- }, function (err) {
- console.log("error in adding employee");
- console.log(err.data);
- });
-
- }
Server side method to add Employee.
- public JsonResult AddEmployee(Employee e)
- {
- using (DemoEntities db = new DemoEntities())
- {
- db.Employees.Add(e);
- db.SaveChanges();
-
- }
- return new JsonResult { Data = "Added Employee", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
- }
Save it and run it. You will see the final output.
Adding an employee
Editing and Updating Employee