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.

Address

Now, let's add a connecting string to our Web. Config file as.

<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <connectionStrings>
        <add name="Test" connectionString="IBALL-PC;Initial Catalog=HotelManagement;Persist Security Info=True;User ID=sa;Password=p@ssw0rd" />
    </connectionStrings>
</configuration>

Now, let's add a Web Service to 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 namespace to this Service.

using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;

We are using this namespace, using System.Web.Script.Serialization; to convert our data to JSON format. Now, uncomment this code as we are using Web Service.

[System.Web.Script.Services.ScriptService]

Now, I have 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.cs

Now, just add these lines to that cs file.

 cs file

Now, let's get back to our Service. In this, we want the list of employees, so add.

public class Employee : System.Web.Services.WebService 
{  
    [WebMethod]  
    public void GetAllEmployees() 
    {  
        List<Employee> listEmployees = new List<Employee>();  
    }  
}

Now, we want to read the connection string from the Web. config file so, we use.

string cs = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
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.

SqlCommand cmd = new SqlCommand("Select * from EmptEst", con);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();

Now, we will be using the while to loop through those records to display on our page.

while (sdr.Read())
{
    Employee employee = new Employee();
    employee.EmpName = sdr["EmpName"].ToString();
    employee.EmpAddress = sdr["EmpAddress"].ToString();
    employee.EmpSalary = Convert.ToInt32(sdr["EmpSalary"]);
}

We add an employee object to the list of employees.

listEmployees.Add(employee);

Now, we have added a namespace, earlier.

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.

[WebMethod]
public void GetAllEmployees()
{
    List<Employee> listEmployees = new List<Employee>();
    string cs = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
    using (SqlConnection con = new SqlConnection(cs))
    {
        SqlCommand cmd = new SqlCommand("Select * from EmptEst", con);
        con.Open();
        SqlDataReader sdr = cmd.ExecuteReader();
        while (sdr.Read())
        {
            Employee employee = new Employee();
            employee.EmpName = sdr["EmpName"].ToString();
            employee.EmpAddress = sdr["EmpAddress"].ToString();
            employee.EmpSalary = Convert.ToInt32(sdr["EmpSalary"]);
            listEmployees.Add(employee);
        }
    }
    JavaScriptSerializer js = new JavaScriptSerializer();
    Context.Response.Write(js.Serialize(listEmployees));
}

Now, we will run the Service and see the output, which we will get.

Output

Let's invoke the Service.

Service

We got JSON output.

SON

Now, we will add an HTML page and display these records. Thus, add an 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 the body tag as our module name and ng-controller in the div tag as our controller name.

Controller name

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

Hence, our Final HTML page is,

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Address</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="employee in employees">
            <td>{{employee.EmpName}}</td>
            <td>{{employee.EmpAddress}}</td>
            <td>{{employee.EmpSalary}}</td>
        </tr>
    </tbody>
</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 the ng-repeat directive and displaying those on the page.

Here, we will write the Service URL and get records.

Initially, our model is given below.

Model

Now, just write this code in your model.

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 ‘service name/function name’, as this will be called Asynchronously. Thus, add another anonymous function i.e. a response adds employees to the $scope object.

var mypartone = angular.module("mymodule", []).controller("myController", function($scope, $http) {  
    $http.get('EmployeeCheck.asmx/GetAllEmployees').then(function(response) {  
        $scope.employees = response.data;  
    });  
});  

Now, save the changes and run the solution.

Solution

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

 Developer tools

The 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.

Post

Thus, our final model code is.

var mypartone = angular.module("mymodule", []).controller("myController", function($scope, $http) {  
    $http.post('EmployeeCheck.asmx/GetAllEmployees').then(function(response) {  
        $scope.employees = response.data;  
    });  
});  

Now, let's reload the page.

Reload

To get the same output as get first in the model, make the 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.

<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <webServices>
        <protocols>
            <add name="HttpGet" />
        </protocols>
    </webServices>
</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.