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
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,
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
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
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 to Fetch All the Employees
- [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 to Insert Employee Records
- [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 to Delete Employee base on Id
- [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;
- }
- }
- //Fetch Record by Id,for Edit/Update
- [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;
- }
- }
- //Update Employee base on Id
- [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.
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.

Join the conversation! Your thoughts help the community grow.