CRUD Operations In Angular Using WebServices In ASP.NET

In this blog I am writing about performing crud operations in Angular 1.0 using Asp.Net WebServices.

What is Angular JS?

Angular JS is a Javascript Framework which helps us build web Applications

Benefits of Angular JS
  1. Dependency Injection
  2. Two Way Data Binding - It keeps model and view in sync,any changes to the model updates the view automatically and any changes to the view changes the model automatically.ng-model directive is used for two way data binding.
  3. Testing
  4. Model View Controller - Angular helps us write code in MVC way the rest that is binding and connecting the components together is done by Angular Framework automatically
  5. Directives,Filter,etc.And in Angular binding expressions are evaluated using {{}} (double curly braces).
Module in AngularJS
  1. A module is a container for different parts of your application i.e. controllers,services,directives,filters etc.
  2. Module is like our main method in other applications.
To create a module we use angular object's module() method.

example- angular.module("myModule",[ ]).Here first parameter is module name and second parameter is optional.

Controller in AngularJs

In angular a controller is a javascript function.The job of controller is to build a model for the view to display. To Create a Controller use following syntax,
  1. var myController = function($scope){  
  2.    $scope.message = "Welcome";  
  3. }  
$scope is angular object that is passed to module,by angular framework automatically.Here,we are attaching message property to $scope object and we will retrive it on view.

Now open sql Server and create a table name it is tblEmployee and it will contain four fields Id which will be identity column,Name,Gender and IsActive.Here is the syntax to create a table
  1. Create table tblEmployee  
  2. (  
  3.    Id int identity,  
  4.    Name varchar(50),  
  5.    Gender varchar(50),  
  6.    IsActive bit  
  7. )  
Next step is to create a stored procedure to insert,update,delete,select the data.Here is the stored procedure I have named it as angular_insert_update_delete
  1. Create procedure angular_insert_update_delete  
  2. (  
  3. @Para varchar(50) = '',  
  4. @Name varchar(50) = '',  
  5. @Gender varchar(50) = '',  
  6. @Id int = 0,  
  7. @IsActive bit = 0  
  8. )  
  9. As  
  10. Begin  
  11. If @Para = 'Select'  
  12. Begin  
  13. Select Id,Name,Gender from tblEmployee where IsActive = 1  
  14. End  
  15. Else If @Para = 'Add'  
  16. Begin  
  17. If Exists(Select 1 from tblEmployee where Name = @Name)  
  18. Begin  
  19. Select 'Exists'  
  20. End  
  21. Else  
  22. Begin  
  23. Insert into tblEmployee (Name,Gender,IsActive) values (@Name,@Gender,1)  
  24. End  
  25. End  
  26. Else If @Para = 'Delete'  
  27. Begin  
  28. Update tblEmployee set IsActive = 0 where Id = @Id  
  29. End  
  30. Else If @Para = 'GetById'  
  31. Begin  
  32. Select Id,Name,Gender from tblEmployee where Id = @Id  
  33. End  
  34. Else If @Para = 'Update'  
  35. Begin  
  36. Update tblEmployee Set Name = @Name,Gender = @Gender where Id = @Id  
  37. End  
  38. End  
Now the next step is to add webservice and the webservice will contain the methods to insert,update,delete the records.

Open visual studio-Select File-New-Project and from template select Asp.Net webforms application and name it as webapplication1 or give any name as you wish.

Now in solutions explorer right click on project-Select-Add-New Item-Select Code from template and then select class to add a class called Emp.This class will contain three properties Id,Name and Gender.Here is the code of Emp Class
  1. public class Emp {  
  2.     public int Id {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Name {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public string Gender {  
  11.         get;  
  12.         set;  
  13.     }  
  14. }  
Now in solutions explorer right click on project-Select-Add-New Item-From the templates select WebService.Give a name to it.In my case it is WebService1.asmx,and to the webservice we will add webmethod to insert, update, delete data, here is the code of webservice.
  1. SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnect"].ToString());  
  2. SqlCommand cmd = null;  
  3. DataTable dt;  
  4. SqlDataAdapter da = null;  
  5. //WebMethod to Fetch All the Employees  
  6. [WebMethod]  
  7. public void GetEmp() {  
  8.     List < Emp > e = new List < Emp > ();  
  9.     using(cmd = new SqlCommand("angular_insert_update_delete", con)) {  
  10.         cmd.CommandType = CommandType.StoredProcedure;  
  11.         cmd.Parameters.AddWithValue("@Para""Select");  
  12.         if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  13.         SqlDataReader dr = cmd.ExecuteReader();  
  14.         while (dr.Read()) {  
  15.             Emp e1 = new Emp();  
  16.             e1.Id = Convert.ToInt32(dr["Id"]);  
  17.             e1.Name = dr["Name"].ToString();  
  18.             e1.Gender = dr["Gender"].ToString();  
  19.             e.Add(e1);  
  20.         }  
  21.         con.Close();  
  22.         JavaScriptSerializer js = new JavaScriptSerializer();  
  23.         Context.Response.Write(js.Serialize(e));  
  24.     }  
  25. }  
  26. //WebMethod to Insert Employee Records  
  27. [WebMethod]  
  28. public int InsertEmp(string Name, string Gender) {  
  29.     string message = string.Empty;  
  30.     using(cmd = new SqlCommand("angular_insert_update_delete", con)) {  
  31.         cmd.CommandType = CommandType.StoredProcedure;  
  32.         cmd.Parameters.AddWithValue("@Para""Add");  
  33.         cmd.Parameters.AddWithValue("@Name", Name);  
  34.         cmd.Parameters.AddWithValue("@Gender", Gender);  
  35.         if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  36.         int result = cmd.ExecuteNonQuery();  
  37.         con.Close();  
  38.         return result;  
  39.     }  
  40. }  
  41. //WebMethod to Delete Employee base on Id  
  42. [WebMethod]  
  43. public int DeleteEmp(string Id) {  
  44.     string message = string.Empty;  
  45.     using(cmd = new SqlCommand("angular_insert_update_delete", con)) {  
  46.         cmd.CommandType = CommandType.StoredProcedure;  
  47.         cmd.Parameters.AddWithValue("@Para""Delete");  
  48.         cmd.Parameters.AddWithValue("@Id", Convert.ToInt32(Id));  
  49.         if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  50.         int result = cmd.ExecuteNonQuery();  
  51.         con.Close();  
  52.         return result;  
  53.     }  
  54. }  
  55. //Fetch Record by Id,for Edit/Update  
  56. [WebMethod]  
  57. public string GetById(string Id) {  
  58.     string Result = string.Empty;  
  59.     using(cmd = new SqlCommand("angular_insert_update_delete", con)) {  
  60.         cmd.CommandType = CommandType.StoredProcedure;  
  61.         cmd.Parameters.AddWithValue("@Para""GetById");  
  62.         cmd.Parameters.AddWithValue("@Id", Convert.ToInt32(Id));  
  63.         if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  64.         dt = new DataTable();  
  65.         da = new SqlDataAdapter(cmd);  
  66.         da.Fill(dt);  
  67.         if (dt.Rows.Count > 0) {  
  68.             Result = "{\"Id\":";  
  69.             Result += "\"" + dt.Rows[0][0].ToString() + "\",";  
  70.             Result += "\"Name\":\"" + dt.Rows[0][1].ToString() + "\",";  
  71.             Result += "\"Gender\":\"" + dt.Rows[0][2].ToString() + "\"";  
  72.             Result += "}";  
  73.         }  
  74.         con.Close();  
  75.         return Result;  
  76.     }  
  77. }  
  78. //Update Employee base on Id  
  79. [WebMethod]  
  80. public int UpdateEmp(string Id, string Name, string Gender) {  
  81.     string message = string.Empty;  
  82.     using(cmd = new SqlCommand("angular_insert_update_delete", con)) {  
  83.         cmd.CommandType = CommandType.StoredProcedure;  
  84.         cmd.Parameters.AddWithValue("@Para""Update");  
  85.         cmd.Parameters.AddWithValue("@Id", Convert.ToInt32(Id));  
  86.         cmd.Parameters.AddWithValue("@Name", Name);  
  87.         cmd.Parameters.AddWithValue("@Gender", Gender);  
  88.         if (con.State.Equals(ConnectionState.Closed)) con.Open();  
  89.         int result = cmd.ExecuteNonQuery();  
  90.         con.Close();  
  91.         return result;  
  92.     }  
  93. }  
First method is GetEmp(),which will return us the list of Employees.Here i have read each value from datareader while it contains data and assign it to properties present in Emp class using Emp class object which is e1.This e1 object is added to generic list of Emp.I have used JavaScriptSerializer to serialize the list.It converts it to json.This JavaScriptSerializer is present in Namespace System.Web.Script.Serialization.
 
The other methods are Insert,Update,Delete to insert,update,delete the Emp records.And one method is GetById to fetch the records base on Id for updation when we click on edit button.From that I have return a string Result,this is in the form of Jquery Object,which I have created using escape sequences(\) in c sharp.
 
Also do not forget to uncomment this line [System.Web.Script.Services.ScriptService] 
 
Now add a connectionstring in webconfig file as follows-
  1. <connectionStrings>  
  2.    <add name="dbConnect" providerName="System.Data.SqlClient" connectionString="Data Source = LIVINGROOM\SQLEXPRESS;Initial Catalog=codefirstDB;Integrated Security=true;"/>  
  3. </connectionStrings>  
Now you can give any name to your connection string,Also data source will be your server name,Initial catalog your databse name.This connection string I have fetched it using SqlConnection class object,you can see on the first line.

Now next step is to add a html page which will be displayed to the user and javascript file where we will write all the code to fetch the data from this webmethod using angular.

Right click on project-Select-Add-New Item-Javascript File to your application and inside it write the following code.
  1. /// <reference path="Scripts/angular.min.js" />  
  2. /// <reference path="Scripts/jquery-1.8.2.min.js" />  
  3. var myApp = angular.module("myModule", []).filter("genderConvert"function() {  
  4.     return function(gender) {  
  5.         switch (gender) {  
  6.             case "1":  
  7.                 return 'Male';  
  8.                 break;  
  9.             case "2":  
  10.                 return "Female";  
  11.                 break;  
  12.         }  
  13.     }  
  14. }).controller("myController"function($scope, $http) {  
  15.     //This value is Set to false,because on page load the div showing records of Employee will displayed if records are present,then myvalue is set to true  
  16.     $scope.myValue = false;  
  17.     //By Default Select is displayed on Gender dropdown so value is set to 0  
  18.     $scope.gender = "0";  
  19.     //This value is used for editing record base on Id  
  20.     $scope.Id = "0";  
  21.     //This value is used to show hide cancel/update/delete button base on conditions  
  22.     $scope.showHide = true;  
  23.     //On page load this method will be called so that records will be displayed in a table format  
  24.     ViewData();  
  25.     //Used to Insert data  
  26.     $scope.InsertData = function(name, gender) {  
  27.         if ((gender == "0" || gender == undefined) || (name == "" || name == undefined)) {  
  28.             alert("Please Select Gender And Enter Name")  
  29.         } else {  
  30.             $http({  
  31.                 method: 'Post',  
  32.                 url: 'WebService1.asmx/InsertEmp',  
  33.                 data: "{'Name' : '" + name + "','Gender' : '" + gender + "'}",  
  34.                 contentType: "application/json; charset=utf-8",  
  35.                 dataType: "json"  
  36.             }).then(function(response) {  
  37.                 clear();  
  38.                 if (response.data.d > 0) {  
  39.                     alert("Record Inserted Successfully");  
  40.                     ViewData();  
  41.                 } else {  
  42.                     alert("Entry Already Exists");  
  43.                     ViewData();  
  44.                 }  
  45.             })  
  46.         }  
  47.     }  
  48.     //Displays all records  
  49.     function ViewData() {  
  50.         $http({  
  51.             method: 'Get',  
  52.             url: 'WebService1.asmx/GetEmp'  
  53.         }).then(function(response) {  
  54.             if (response.data.length > 0) {  
  55.                 $scope.emp = response.data;  
  56.                 $scope.myValue = true;  
  57.             } else {  
  58.                 $scope.myValue = false;  
  59.             }  
  60.         })  
  61.     }  
  62.     //Delete Record on base of Id  
  63.     $scope.DeleteData = function(Id) {  
  64.         if (window.confirm("Are you sure you want to Delete this record?")) $scope.result = "Yes";  
  65.         else $scope.result = "No";  
  66.         if ($scope.result == "Yes") {  
  67.             $http({  
  68.                 method: 'Post',  
  69.                 url: 'WebService1.asmx/DeleteEmp',  
  70.                 data: "{'Id' : '" + Id + "'}",  
  71.                 contentType: "application/json; charset=utf-8",  
  72.                 dataType: "json"  
  73.             }).then(function(response) {  
  74.                 if (response.data.d > 0) {  
  75.                     alert("Record Deleted Successfully");  
  76.                     ViewData();  
  77.                 } else {  
  78.                     alert("Record Not Deleted");  
  79.                     ViewData();  
  80.                 }  
  81.             })  
  82.         }  
  83.     }  
  84.     //Edit on base of Id  
  85.     $scope.EditData = function(Id) {  
  86.         $http({  
  87.             method: 'Post',  
  88.             url: 'WebService1.asmx/GetById',  
  89.             data: "{'Id' : '" + Id + "'}",  
  90.             contentType: "application/json; charset=utf-8",  
  91.             dataType: "json"  
  92.         }).then(function(response) {  
  93.             if (response.data.d.length > 0) {  
  94.                 var Result = jQuery.parseJSON(response.data.d);  
  95.                 $scope.Id = Result.Id;  
  96.                 $scope.name = Result.Name;  
  97.                 $scope.gender = Result.Gender;  
  98.                 $scope.showHide = false;  
  99.             }  
  100.         })  
  101.     }  
  102.     //If we want to cancel update this method is called on Cancel click  
  103.     $scope.CancelUpdate = function() {  
  104.         $scope.name = " ";  
  105.         $scope.gender = "0";  
  106.         $scope.Id = "0";  
  107.         $scope.showHide = true;  
  108.     }  
  109.     //Update records  
  110.     $scope.UpdateData = function(Id, name, gender) {  
  111.         if ((gender == "0" || gender == undefined) || (name == "" || name == undefined)) {  
  112.             alert("Please Select Gender And Enter Name")  
  113.         } else {  
  114.             $http({  
  115.                 method: 'Post',  
  116.                 url: 'WebService1.asmx/UpdateEmp',  
  117.                 data: "{'Id' : '" + Id + "','Name' : '" + name + "','Gender' : '" + gender + "'}",  
  118.                 contentType: "application/json; charset=utf-8",  
  119.                 dataType: "json"  
  120.             }).then(function(response) {  
  121.                 clear();  
  122.                 if (response.data.d > 0) {  
  123.                     alert("Record Updated Successfully");  
  124.                     ViewData();  
  125.                 } else {  
  126.                     alert("Record Not Updated");  
  127.                     ViewData();  
  128.                 }  
  129.             })  
  130.         }  
  131.     }  
  132.     //To Reset all values  
  133.     function clear() {  
  134.         $scope.name = "";  
  135.         $scope.gender = "0";  
  136.         $scope.Id = "0";  
  137.         $scope.showHide = true;  
  138.     }  
  139. });  
Now it is very important to add reference of angular js script file to your project.As you can see on first line I have added reference of angular script file.You can download this file from angular.org
 
Now on the next line i have used angular object's module method to create a module,first parameter is module name which is myModule and second parameter is optional.Then I have used filter method to create a filter.First parameter is filter name which is genderConvert and in angular filter is a function which returns another function,as you can see I have return function which converts gender to male and female 1 is for male and 2 is for female.
 
Now next is controller method which is used to create a controller,first parameter is controller name which is myController,and a controller is a javascript function.To this function I have passed two parameters one is $scope and other one is $http,this $http is used to call webservice I will discuss it later.
 
Now to the $scope I have attached property myValue to that value assigned is false,this is used to display the div containing employee records and hide it when no records are present on page load on view i.e.html page.
 
Next property attach is gender which is set to 0,so this will set by default value Select to the gender drop down on page load.
 
Next property is Id which is used to update and delete records on base of Id.
 
Now on the page there is a method ViewData() which is use to display employee records on page load.Now in
this method I have used $http object,it has various properties first is method its type is Get,as we are not posting any data and second is url to this we have assigned url of webmethod.Then there is then function,it is like success function which has recieved response from the webmethod,it contains data property and this value is assigned to emp property attached to scope object.This emp property will be used to display emp records on view.Base upon wether response object contains data or not I have set myValue property to false or true.
 
Now second method is insertdata which is used to insert the records,in that method I have checked wether gender and name is selected or not if not alert is displayed else Insert webmethod is called.Now again to the $http object first property is method type is Post as we are posting the data,then url which is used to call webmethod,data contains the data to be passed to webmethod and datatype is json and next is success function which is then which will contain the response generated on successful insertion it will be 1 and there will be negative value if insertion is not successful,according to that i have displayed the alert.
 
Next is editdata method which will be called on edit button click to fetch record base on id,to that we are passing Id of record and base on that Id we are fetching details of that particular record.
 
Next method is deletedata to which I have passed Id of record and based upon Id record will be deleted.In the method first I have asked the user wether he is confirm to delete the data and value user selects is assigned to result property attached to $scope object,if value is yes record will be deleted and if it is no then it will be cancelled.
 
Next method is updatedata to this method I have passed Id base upon the Id record will be updated and gender and name the properties need to be updated.
 
Next method is clear which will reset all the values upon insertion and updation.
 
Next is cancelupdate which is used to cancel the updation.
 
Now next step is to add a html page which will display the data to user,Right click on project-Add-New Item-Select html page from the template and on the html page write the following code.
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml" ng-app="myModule">  
  3.   
  4. <head>  
  5.     <script src="Scripts/angular.min.js" type="text/javascript" lang="ja"></script>  
  6.     <script src="Scripts/jquery-1.8.2.min.js" type="text/javascript" lang="ja"></script>  
  7.     <script src="JavaScript13.js" type="text/javascript" lang="ja"></script>  
  8.     <title></title>  
  9. </head>  
  10.   
  11. <body ng-controller="myController"> Enter Name : <input type="text" ng-model="name" /> <br /> Select Gender : <select ng-model="gender">  
  12. <option value="0">Select</option>  
  13. <option value="1">Male</option>  
  14. <option value="2">Female</option>  
  15. </select> <br /> <br /> <input type="button" value="Submit" ng-click="InsertData(name,gender)" ng-show="showHide" /> <input type="button" value="Update" ng-click="UpdateData(Id,name,gender)" ng-hide="showHide" /> <input type="button" value="Camcel" ng-click="CancelUpdate()" ng-hide="showHide" /> <br /> <br />  
  16.     <div ng-show="myValue">  
  17.         <table border="1">  
  18.             <tr>  
  19.                 <th>Id</th>  
  20.                 <th>Name</th>  
  21.                 <th>Gender</th>  
  22.                 <th>Action</th>  
  23.             </tr>  
  24.             <tr ng-repeat="e in emp">  
  25.                 <td>{{e.Id}}</td>  
  26.                 <td>{{e.Name}}</td>  
  27.                 <td>{{e.Gender | genderConvert}}</td>  
  28.                 <td> <input type="button" value="Edit" ng-click="EditData(e.Id)" /> <input type="button" value="Delete" ng-click="DeleteData(e.Id)" /> </td>  
  29.             </tr>  
  30.         </table>  
  31.     </div>  
  32. </body>  
  33.   
  34. </html>  
Now in the head section I have added reference of three scripts first angular.min.js,second is jquery 1.8.2.min.js and third is our js file where I have written the code to insert,update,delete records.Remember the order of the script is important.
 
Now to the html tag i have attached ng-app directive and to ng-app i have assigned module name which is myModule given when we created module using angular object's module method.ng-app is starting point of angular application,ng stands for angular as soon as angular framework finds ng-app directive it bootstraps itself and starts managing the section of code which is under ng-app directive.
 
To the body tag i have assigned ng-controller directive to which I have assigned name of the controller which is myController.
 
Next I have taken a html textbox to enter name of the employee,I have used ng-model and to that I have assigned name property,as discussed ng-model is used for two way data binding whatever value we insert here that will be assigned to name property of the $scope object in controller and vice versa.
 
Next there is a dropdown to select gender,in this also I have used ng-model to which I have assigned gender property value,it is set to 0 on controller,so when we load the page by default value will be select in the dropdown.
 
Next I have taken three buttons for insert,update and delete and made them clickable using ng-click directive,on its click I have called respective methods from controller.With the button I have used ng-show and ng-hide directive to show and hide the buttons.To this directive showHide property is assigned its values is set to true on controller,so by default submit button will be visible on page load and the other button will not be visible.As for the other two I have set ng-hide to true.
 
Now there is a div which is use to display emp records,you can see I have used ng-show directive and to that I have assigned myValue property which is set to false on controller,so on page load this div will not be visible if no records are presnet when records are inserted myValue property will become true and div will be visible.
 
Now there is a table inside this div,in which I have displayed records of employee.I have used ng-repeat it is like foreach loop.In this I have iterated over emp property which contains all emp values and displayed each field of it like its Id,Name and Gender.Also table contains two buttons for edit and delete and again they had been made clickable using ng-click directive and the respective methods are called.
 
Now the last change is write the following code in web.config file inside system.web tag inside webservices tag,then protocols and add name for Protocols as HttpGet and HttpPost
  1. <webServices>  
  2.     <protocols>  
  3.         <add name="HttpGet" />  
  4.         <add name="HttpPost" /> </protocols>  
  5. </webServices>  
Build and run the application by setting the html page as start page
Ebook Download
View all
Learn
View all