CRUD Operation Using HTML+ Angular Along With WebAPI

We often design in pure HTML and use JS to make an application more interactive and responsive. In that, using Angular JS it'll make it more efficient and interactive from an operational point of view.

Web API is always working in the background to connect with the database and provide a required view to the front end.

Here we are designing on HTML and Angular to make it lightweight and using Web API to perform database activities.

Code to Load Value from database to HTML table:

Angular Code
  1. var app = angular.module('myApp', []);  
  2. app.controller('formCtrl'function($scope, $http) {  
  3.     $scope.info = [];  
  4.     $scope.loadPeople = function() {  
  5.         $scope.info = [];  
  6.         var httpRequest = $http({  
  7.             method: 'GET',  
  8.             url: "http://www.webapi.com/Operation/GetDetail", // Calling WebAPI and its Get Method to get detail.  
  9.             data: ""  
  10.         }).then(function successCallback(response) {  
  11.             result = response.data;  
  12.             var obj = JSON.parse(result); // Converting response data into an object  
  13.             angular.forEach(obj, function(obj) {  
  14.                 $scope.info.push(obj); //  Pusing every object into a Scope to bind with HTML Table  
  15.             });  
  16.         }, function errorCallback(response) {});  
  17.     };  
  18.     $scope.loadPeople(); // Calling loadPeople function on load of HTML Page  
  19. });  
HTML Code
  1. <table id="tblExport" class="table table-bordered" ng-show="info.length>0">  
  2.     <tr>  
  3.         <th ng-click="SortAsc('first')">First Name</th>  
  4.         <th>Last Name</th>  
  5.         <th ng-click="SortAsc('course')">Course</th>  
  6.         <th ng-click="SortAsc('fees')">Fees</th>  
  7.         <td>Remove</td>  
  8.         <td>Edit</td>  
  9.     </tr>  
  10.     <tr ng-repeat="i in info|filter:searchVal| orderBy:myVal">  
  11.         <!-- Repeating each list and binding with new tr of a table.  -->  
  12.         <td style="display:none;">{{i.id}}</td>  
  13.         <td>{{i.firstName}}</td>  
  14.         <td>{{i.lastName}}</td>  
  15.         <td>{{i.course}}</td>  
  16.         <td>{{i.fees}}</td>  
  17.         <td><span ng-click="DeleteInfoAPI($index)">X</span></td>  
  18.         <td><span ng-click="Edit($index)">Edit</span></td>  
  19.     </tr>  
  20. </table>  

WebAPI Method to Get data,
  1. [HttpGet]  
  2. [Route("GetDetail")]  
  3. public string GetInfo() {  
  4.     ApiBAL.ApiBAL BAL = new ApiBAL.ApiBAL();  
  5.     List < InfoModel > infoList = new List < InfoModel > ();  
  6.     DataTable dtTable = BAL.GetDataTable_SQL("Select * from tblinfo""trainingdb");  
  7.     infoList = ApiBAL.Helper.DataTableToList < InfoModel > (dtTable); // Converting datatable to list of mentioned type i.e "InfoModel"  
  8.     // Serialized the list into Json String  
  9.     String serializedString = JsonConvert.SerializeObject(ApiBAL.Helper.DataTableToList < InfoModel > (dtTable));  
  10.     return serializedString;  
  11. }  
Angular & WebAPI Method to save data:

Angular
  1. $scope.AddInfoAPI = function() {  
  2.         if ($scope.mySelect != "-1") {  
  3.             var info = {};  
  4.             var result;  
  5.             // create an object to send as a data   
  6.             info = {  
  7.                 firstName: $scope.firstName,  
  8.                 lastName: $scope.lastName,  
  9.                 course: $scope.mySelect,  
  10.                 fees: $scope.fees  
  11.             };  
  12.             $.ajax({  
  13.                 type: "POST",  
  14.                 url: "http://www.webapi.com/Operation/SaveDetail",  
  15.                 cache: false,  
  16.                 dataType: "json",  
  17.                 contentType: 'application/json; charset=utf-8',  
  18.                 //Sending an object into a json string using "Stringify" method  
  19.                 data: JSON.stringify(info),  
  20.                 //async: false,  
  21.                 success: function(response) {  
  22.                     result = response;  
  23.                     if (result == 'Done') {  
  24.                         alert('Record added successfully');  
  25.                         $scope.loadPeople();  
  26.                     }  
  27.                 }  
  28.             }).fail(function(jqXHR, textStatus, errorThrown) {  
  29.                 alert(errorThrown);  
  30.                 result = null;  
  31.             });  
  32.             clearField();  
  33.         } else {  
  34.             alert("Please select Valid Course.")  
  35.         }  
  36.     }  
  37.     [HttpPost]  
  38.     [Route("SaveDetail")]  
  39. public string SaveInfo([FromBody] InfoModel info) // Using [FromBody] we receive whole list in a type model to process.  
  40. {  
  41.     ApiBAL.ApiBAL BAL = new ApiBAL.ApiBAL();  
  42.     Hashtable ht = new Hashtable();  
  43.     ht.Add("@type""Save");  
  44.     ht.Add("@firstName", info.firstName);  
  45.     ht.Add("@lastName", info.lastName);  
  46.     ht.Add("@course", info.course);  
  47.     ht.Add("@fees", info.fees);  
  48.     string result = BAL.SaveData_SQL(ht, "basicCRUD""TrainingDB");  
  49.     return result;  
  50. }  
Saving details is the same way  we do it  in C# using SQL client code. All we need to do is check data serialization over the network to save and display.

In this process we can also remove or update details using web API methods which are as follows.
  1. //--------------------------------------Update a record using webAPI method via angular function call-----------------  
  2. [Route("UpdateDetail")]  
  3. [HttpPost]  
  4. public string UpdateInfo([FromBody] InfoModel info) {  
  5.     ApiBAL.ApiBAL BAL = new ApiBAL.ApiBAL();  
  6.     Hashtable ht = new Hashtable();  
  7.     ht.Add("@type""Update");  
  8.     ht.Add("@id", info.id);  
  9.     ht.Add("@firstName", info.firstName);  
  10.     ht.Add("@lastName", info.lastName);  
  11.     ht.Add("@course", info.course);  
  12.     ht.Add("@fees", info.fees);  
  13.     string result = BAL.SaveData_SQL(ht, "basicCRUD""TrainingDB");  
  14.     return result;  
  15. }  
  16. $scope.UpdateInfoAPI = function() {  
  17.     if ($scope.mySelect != "-1") {  
  18.         var result;  
  19.         info = {  
  20.             id: $scope.id,  
  21.             firstName: $scope.firstName,  
  22.             lastName: $scope.lastName,  
  23.             course: $scope.mySelect,  
  24.             fees: $scope.fees  
  25.         };  
  26.         $.ajax({  
  27.             type: "POST",  
  28.             url: "http://www.webapi.com/Operation/UpdateDetail",  
  29.             cache: false,  
  30.             dataType: "json",  
  31.             contentType: 'application/json; charset=utf-8',  
  32.             //data: _data,  
  33.             data: JSON.stringify(info),  
  34.             //async: false,  
  35.             success: function(response) {  
  36.                 result = response;  
  37.                 if (result == 'Done') {  
  38.                     $scope.loadPeople();  
  39.                     alert('Record updated successfully');  
  40.                 }  
  41.             }  
  42.         }).fail(function(jqXHR, textStatus, errorThrown) {  
  43.             alert(errorThrown);  
  44.             result = null;  
  45.         });  
  46.         $scope.chk = false;  
  47.         clearField();  
  48.     }  
  49. }  
  50. //--------------------------------------Delete a record using webAPI method via angular function call-----------------   
  51. [Route("DeleteDetail")]  
  52. [HttpPost]  
  53. public int DeleteInfo([FromBody] InfoModel info) {  
  54.     int id = info.id;  
  55.     ApiBAL.ApiBAL BAL = new ApiBAL.ApiBAL();  
  56.     int result = BAL.SaveData_SQL("delete from tblinfo where id=" + id, "traingindb");  
  57.     return result;  
  58. }  
  59. $scope.DeleteInfoAPI = function(index) {  
  60.     var id = $scope.info[index].id;  
  61.     info = {  
  62.         id: id  
  63.     };  
  64.     var httpreques = $http({  
  65.         method: 'POST',  
  66.         url: "http://www.webapi.com/Operation/DeleteDetail",  
  67.         data: JSON.stringify(info),  
  68.     }).then(function success() {  
  69.         alert("Detail deleted successfully");  
  70.         $scope.loadPeople();  
  71.     }, function errorCallback(response) {  
  72.         /  
  73.     });  
  74. }  
In the above example a CRUD operation has been performed using WebAPI and the results are bound in HTML form using Angular js.

For reference, I will be attaching an HTML file from where a Web API call is made to access the database.

All references and code have been mentioned in the above blog.

Good day!!