Consuming ASP.NET WebService In AngularJS

Overview

In this article, we will see ASP.NET Web Service and how to use or implement it in Angular JS. In a table, I have the data, which is called employees. We want to display the data with the help of ASP.NET Web Service and display in our view. Thus, let's see with an example.

For more articles on Angular JS refer to,

Introduction

In SQL, I already have a table, which is employee details, which has Name, address, Salary and so on.

details

Now, let's add a connecting string in our Web. Config file as:
  1. <configuration>  
  2.     <system.web>  
  3.         <compilation debug="true" targetFramework="4.0" /> </system.web>  
  4.     <connectionStrings>  
  5.         <add name="Test" connectionString="IBALL-PC;Initial Catalog=HotelManagement;Persist Security Info=True;User ID=sa;Password=p@ssw0rd" /> </connectionStrings>  
  6. </configuration>  
Now, let's add a Web Service in our solution. Right click the Solution ->Add new Item -> Name that service as Employee.

Item

Name it as Employee.asmx.

web service

Now, let's add some name space to this Service as:
  1. using System.Configuration;  
  2. using System.Data.SqlClient;  
  3. using System.Web.Script.Serialization;  
We are using this namespace, using System.Web.Script.Serialization; to covert our data to JSON format. Now, uncomment this code as we are using Web Service,

[System.Web.Script.Services.ScriptService]

Now, I had changed the function to Get AllEmployees() and it will return the list of all the employees. Thus, we add an Employee.c s file. In this, we assign these properties as:

Right click on the solution again -> Add new Item -> class File->name it as Employee.cs.

class

Name it as Employee.cs.

Employee

Now, just add these lines in that cs file.

 cs file

Now, let's get back to our Service. In this, we want the list of employees, so add:
  1. public class Employee: System.Web.Services.WebService {  
  2.     [WebMethod]  
  3.     public void GetAllEmployees() {  
  4.         List < Employee > listEmployees = new List < Employee > ();  
  5.     }  
  6. }  
Now, we want to read the connection string from Web.config file so, we use:
  1. string cs = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;  
  2. using (SqlConnection con = new SqlConnection(cs))  
The name of our connection string is Test. Now, we will pass the table by SQL command and execute the command:
  1. SqlCommand cmd = new SqlCommand("Select * from EmptEst", con);  
  2. con.Open();  
  3. SqlDataReader sdr = cmd.ExecuteReader();  
Now, we will be using the while to loop through those records to display on our page:
  1. while (sdr.Read())  
  2. {  
  3.     Employee employee = new Employee();  
  4.     employee.EmpName = sdr["EmpName"].ToString();  
  5.     employee.EmpAddress = sdr["EmpAddress"].ToString();  
  6.     employee.EmpSalary = Convert.ToInt32(sdr["EmpSalary"]);  
  7. }  
We add an employee object to list of employees,

listEmployees.Add(employee);

Now, we have added a name space, earlier as:

using System.Web.Script.Serialization;

We will be using this property to display the records in JSON format.

JavaScriptSerializer js = new JavaScriptSerializer();

We will pass the records in context.write and serialize the list of employees:

Context.Response.Write(js.Serialize(listEmployees));

Our final Service Code is:
  1. [WebMethod]  
  2. public void GetAllEmployees() {  
  3.     List < Employee > listEmployees = new List < Employee > ();  
  4.     string cs = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;  
  5.     using(SqlConnection con = new SqlConnection(cs)) {  
  6.         SqlCommand cmd = new SqlCommand("Select * from EmptEst", con);  
  7.         con.Open();  
  8.         SqlDataReader sdr = cmd.ExecuteReader();  
  9.         while (sdr.Read()) {  
  10.             Employee employee = new Employee();  
  11.             employee.EmpName = sdr["EmpName"].ToString();  
  12.             employee.EmpAddress = sdr["EmpAddress"].ToString();  
  13.             employee.EmpSalary = Convert.ToInt32(sdr["EmpSalary"]);  
  14.             listEmployees.Add(employee);  
  15.         }  
  16.     }  
  17.     JavaScriptSerializer js = new JavaScriptSerializer();  
  18.     Context.Response.Write(js.Serialize(listEmployees));  
  19. }  
Now, we will run the Service and see the output, which we will get:

output

Lets invoke the Service:

output

We got JSON output.

output

Now, we will add HTML page and display these records. Thus, add HTML page by right clicking on the solution->Html page ->Name it as Display.html, as given below:

Html

In our HTML page, I added ng-app in body tag as our module name and ng-controller in div tag as our controller name:

HTML

Now, here we will add a table tag an inside the table. We will then display the header and tr and use ng-repat directive to loop through these records.

Hence, our Final HTML page is:
  1. <table>  
  2.     <thead>  
  3.         <tr>  
  4.             <th>Name</th>  
  5.             <th>Address</th>  
  6.             <th>Salary</th>  
  7.         </tr>  
  8.     </thead>  
  9.     <tbody>  
  10.         <tr ng-repeat="employee in employees">  
  11.             <td> {{employee.EmpName}} </td>  
  12.             <td>{{employee.EmpAddress}}</td>  
  13.             <td>{{employee.EmpSalary}}</td>  
  14.         </tr>  
  15.     </tbody>  
  16. </table>  
Now, let's get back to our controller. Initially, we had been hard coding our records and looping through these records with the help of ng-repeat directive and displaying those on the page.

Here, we will write Service URL and get records .

Initially, our model is given below:

model

Now, just write this code in your model as:

In function, I am passing $http to get the response from our service and in $http.get, we will write the Service name and function name as ‘servicename/functionname’, as this will be called Asynchronously. Thus, add another anonymous function i.e. a response add employees to $scope object.
  1. var mypartone = angular.module("mymodule", []).controller("myController"function($scope, $http) {  
  2.     $http.get('EmployeeCheck.asmx/GetAllEmployees').then(function(response) {  
  3.         $scope.employees = response.data;  
  4.     });  
  5. });  
Now, save the changes and run the solution.

solution

As you had seen, we didn’t get any data. Let's see the developer tools:

solution

Error says the status of 500 (internal server error).

Why is this coming? We are using get here in our model.

code

Just change it to post as,

code

Thus, our final model code is:
  1. var mypartone = angular.module("mymodule", []).controller("myController"function($scope, $http) {  
  2.     $http.post('EmployeeCheck.asmx/GetAllEmployees').then(function(response) {  
  3.         $scope.employees = response.data;  
  4.     });  
  5. });  
Now, let's reload the page:

Page

To get the same output with get first in the model, make change as .get as:

$http.get('EmployeeCheck.asmx/GetAllEmployees')

Now, go to Web.config file. In this under <system.web> section, just make a section as:
  1. <system.web>  
  2.     <compilation debug="true" targetFramework="4.0" />  
  3.     <webServices>  
  4.         <protocols>  
  5.             <add name="HttpGet" /> </protocols>  
  6.     </webServices>  
  7. </system.web>  
Now, reload the page.

Page

We got an output by using get request and no errors, when you look in the developer tools. We got an output and we displayed the data from the database through our Web Service in Angular JS.

Conclusion:
Thus, this was consuming ASP.NET Web Service in AngularJS.

Up Next
    Ebook Download
    View all
    Learn
    View all