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
- Dependency Injection
- 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.
- Testing
- 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
- Directives,Filter,etc.And in Angular binding expressions are evaluated using {{}} (double curly braces).
Module in AngularJS
- A module is a container for different parts of your application i.e. controllers,services,directives,filters etc.
- 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,
- var myController = function($scope){
- $scope.message = "Welcome";
- }
$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
- Create table tblEmployee
- (
- Id int identity,
- Name varchar(50),
- Gender varchar(50),
- IsActive bit
- )
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
- Create procedure angular_insert_update_delete
- (
- @Para varchar(50) = '',
- @Name varchar(50) = '',
- @Gender varchar(50) = '',
- @Id int = 0,
- @IsActive bit = 0
- )
- As
- Begin
- If @Para = 'Select'
- Begin
- Select Id,Name,Gender from tblEmployee where IsActive = 1
- End
- Else If @Para = 'Add'
- Begin
- If Exists(Select 1 from tblEmployee where Name = @Name)
- Begin
- Select 'Exists'
- End
- Else
- Begin
- Insert into tblEmployee (Name,Gender,IsActive) values (@Name,@Gender,1)
- End
- End
- Else If @Para = 'Delete'
- Begin
- Update tblEmployee set IsActive = 0 where Id = @Id
- End
- Else If @Para = 'GetById'
- Begin
- Select Id,Name,Gender from tblEmployee where Id = @Id
- End
- Else If @Para = 'Update'
- Begin
- Update tblEmployee Set Name = @Name,Gender = @Gender where Id = @Id
- End
- 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
- public class Emp {
- public int Id {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public string Gender {
- get;
- set;
- }
- }
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.
- SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnect"].ToString());
- SqlCommand cmd = null;
- DataTable dt;
- SqlDataAdapter da = null;
-
- [WebMethod]
- public void GetEmp() {
- List < Emp > e = new List < Emp > ();
- using(cmd = new SqlCommand("angular_insert_update_delete", con)) {
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Para", "Select");
- if (con.State.Equals(ConnectionState.Closed)) con.Open();
- SqlDataReader dr = cmd.ExecuteReader();
- while (dr.Read()) {
- Emp e1 = new Emp();
- e1.Id = Convert.ToInt32(dr["Id"]);
- e1.Name = dr["Name"].ToString();
- e1.Gender = dr["Gender"].ToString();
- e.Add(e1);
- }
- con.Close();
- JavaScriptSerializer js = new JavaScriptSerializer();
- Context.Response.Write(js.Serialize(e));
- }
- }
-
- [WebMethod]
- public int InsertEmp(string Name, string Gender) {
- string message = string.Empty;
- using(cmd = new SqlCommand("angular_insert_update_delete", con)) {
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Para", "Add");
- cmd.Parameters.AddWithValue("@Name", Name);
- cmd.Parameters.AddWithValue("@Gender", Gender);
- if (con.State.Equals(ConnectionState.Closed)) con.Open();
- int result = cmd.ExecuteNonQuery();
- con.Close();
- return result;
- }
- }
-
- [WebMethod]
- public int DeleteEmp(string Id) {
- string message = string.Empty;
- using(cmd = new SqlCommand("angular_insert_update_delete", con)) {
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Para", "Delete");
- cmd.Parameters.AddWithValue("@Id", Convert.ToInt32(Id));
- if (con.State.Equals(ConnectionState.Closed)) con.Open();
- int result = cmd.ExecuteNonQuery();
- con.Close();
- return result;
- }
- }
-
- [WebMethod]
- public string GetById(string Id) {
- string Result = string.Empty;
- using(cmd = new SqlCommand("angular_insert_update_delete", con)) {
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Para", "GetById");
- cmd.Parameters.AddWithValue("@Id", Convert.ToInt32(Id));
- if (con.State.Equals(ConnectionState.Closed)) con.Open();
- dt = new DataTable();
- da = new SqlDataAdapter(cmd);
- da.Fill(dt);
- if (dt.Rows.Count > 0) {
- Result = "{\"Id\":";
- Result += "\"" + dt.Rows[0][0].ToString() + "\",";
- Result += "\"Name\":\"" + dt.Rows[0][1].ToString() + "\",";
- Result += "\"Gender\":\"" + dt.Rows[0][2].ToString() + "\"";
- Result += "}";
- }
- con.Close();
- return Result;
- }
- }
-
- [WebMethod]
- public int UpdateEmp(string Id, string Name, string Gender) {
- string message = string.Empty;
- using(cmd = new SqlCommand("angular_insert_update_delete", con)) {
- cmd.CommandType = CommandType.StoredProcedure;
- cmd.Parameters.AddWithValue("@Para", "Update");
- cmd.Parameters.AddWithValue("@Id", Convert.ToInt32(Id));
- cmd.Parameters.AddWithValue("@Name", Name);
- cmd.Parameters.AddWithValue("@Gender", Gender);
- if (con.State.Equals(ConnectionState.Closed)) con.Open();
- int result = cmd.ExecuteNonQuery();
- con.Close();
- return result;
- }
- }
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-
- <connectionStrings>
- <add name="dbConnect" providerName="System.Data.SqlClient" connectionString="Data Source = LIVINGROOM\SQLEXPRESS;Initial Catalog=codefirstDB;Integrated Security=true;"/>
- </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.
-
-
- var myApp = angular.module("myModule", []).filter("genderConvert", function() {
- return function(gender) {
- switch (gender) {
- case "1":
- return 'Male';
- break;
- case "2":
- return "Female";
- break;
- }
- }
- }).controller("myController", function($scope, $http) {
-
- $scope.myValue = false;
-
- $scope.gender = "0";
-
- $scope.Id = "0";
-
- $scope.showHide = true;
-
- ViewData();
-
- $scope.InsertData = function(name, gender) {
- if ((gender == "0" || gender == undefined) || (name == "" || name == undefined)) {
- alert("Please Select Gender And Enter Name")
- } else {
- $http({
- method: 'Post',
- url: 'WebService1.asmx/InsertEmp',
- data: "{'Name' : '" + name + "','Gender' : '" + gender + "'}",
- contentType: "application/json; charset=utf-8",
- dataType: "json"
- }).then(function(response) {
- clear();
- if (response.data.d > 0) {
- alert("Record Inserted Successfully");
- ViewData();
- } else {
- alert("Entry Already Exists");
- ViewData();
- }
- })
- }
- }
-
- function ViewData() {
- $http({
- method: 'Get',
- url: 'WebService1.asmx/GetEmp'
- }).then(function(response) {
- if (response.data.length > 0) {
- $scope.emp = response.data;
- $scope.myValue = true;
- } else {
- $scope.myValue = false;
- }
- })
- }
-
- $scope.DeleteData = function(Id) {
- if (window.confirm("Are you sure you want to Delete this record?")) $scope.result = "Yes";
- else $scope.result = "No";
- if ($scope.result == "Yes") {
- $http({
- method: 'Post',
- url: 'WebService1.asmx/DeleteEmp',
- data: "{'Id' : '" + Id + "'}",
- contentType: "application/json; charset=utf-8",
- dataType: "json"
- }).then(function(response) {
- if (response.data.d > 0) {
- alert("Record Deleted Successfully");
- ViewData();
- } else {
- alert("Record Not Deleted");
- ViewData();
- }
- })
- }
- }
-
- $scope.EditData = function(Id) {
- $http({
- method: 'Post',
- url: 'WebService1.asmx/GetById',
- data: "{'Id' : '" + Id + "'}",
- contentType: "application/json; charset=utf-8",
- dataType: "json"
- }).then(function(response) {
- if (response.data.d.length > 0) {
- var Result = jQuery.parseJSON(response.data.d);
- $scope.Id = Result.Id;
- $scope.name = Result.Name;
- $scope.gender = Result.Gender;
- $scope.showHide = false;
- }
- })
- }
-
- $scope.CancelUpdate = function() {
- $scope.name = " ";
- $scope.gender = "0";
- $scope.Id = "0";
- $scope.showHide = true;
- }
-
- $scope.UpdateData = function(Id, name, gender) {
- if ((gender == "0" || gender == undefined) || (name == "" || name == undefined)) {
- alert("Please Select Gender And Enter Name")
- } else {
- $http({
- method: 'Post',
- url: 'WebService1.asmx/UpdateEmp',
- data: "{'Id' : '" + Id + "','Name' : '" + name + "','Gender' : '" + gender + "'}",
- contentType: "application/json; charset=utf-8",
- dataType: "json"
- }).then(function(response) {
- clear();
- if (response.data.d > 0) {
- alert("Record Updated Successfully");
- ViewData();
- } else {
- alert("Record Not Updated");
- ViewData();
- }
- })
- }
- }
-
- function clear() {
- $scope.name = "";
- $scope.gender = "0";
- $scope.Id = "0";
- $scope.showHide = true;
- }
- });
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.
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml" ng-app="myModule">
-
- <head>
- <script src="Scripts/angular.min.js" type="text/javascript" lang="ja"></script>
- <script src="Scripts/jquery-1.8.2.min.js" type="text/javascript" lang="ja"></script>
- <script src="JavaScript13.js" type="text/javascript" lang="ja"></script>
- <title></title>
- </head>
-
- <body ng-controller="myController"> Enter Name : <input type="text" ng-model="name" /> <br /> Select Gender : <select ng-model="gender">
- <option value="0">Select</option>
- <option value="1">Male</option>
- <option value="2">Female</option>
- </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 />
- <div ng-show="myValue">
- <table border="1">
- <tr>
- <th>Id</th>
- <th>Name</th>
- <th>Gender</th>
- <th>Action</th>
- </tr>
- <tr ng-repeat="e in emp">
- <td>{{e.Id}}</td>
- <td>{{e.Name}}</td>
- <td>{{e.Gender | genderConvert}}</td>
- <td> <input type="button" value="Edit" ng-click="EditData(e.Id)" /> <input type="button" value="Delete" ng-click="DeleteData(e.Id)" /> </td>
- </tr>
- </table>
- </div>
- </body>
-
- </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
- <webServices>
- <protocols>
- <add name="HttpGet" />
- <add name="HttpPost" /> </protocols>
- </webServices>
Build and run the application by setting the html page as start page