How To Implement Angular Data Table With CRUD Using ASP
How To Implement Angular Data Table With CRUD Using ASP
How To Implement Angular Data Table With CRUD Using ASP
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.
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
Step 3 - Implementation
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.
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.
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. ];
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.
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.
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. 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.
Create one Angular Service to call the server side method as it is similar to AJAX call in jQuery.
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.
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.
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. //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.
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. }
Save it and run it. You will see the final output.
Adding an employee