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.
Now, let's add a connecting string in 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 in our solution. Right click the Solution ->Add new Item -> Name that service as Employee.
Name it as Employee.asmx.
Now, let's add some name space to this Service as:
- using System.Configuration;
- using System.Data.SqlClient;
- 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.
Name it as Employee.cs.
Now, just add these lines in that 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 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 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:
- [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:
Lets invoke the Service:
We got JSON 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:
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:
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:
- <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 ng-repeat directive and displaying those on the page.
Here, we will write Service URL and get records .
Initially, our model is given below:
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.
- 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.
As you had seen, we didn’t get any data. Let's see the developer tools:
Error says the status of 500 (internal server error).
Why is this coming? We are using get here in our model.
Just change it to post as,
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:
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:
- <system.web>
- <compilation debug="true" targetFramework="4.0" />
- <webServices>
- <protocols>
- <add name="HttpGet" /> </protocols>
- </webServices>
- </system.web>
Now, reload the 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.