Consuming Web Service Using ASP.NET AJAX

ASP.NET AJAX provides the power of asynchronous JavaScript and XML to your web sites. AJAX makes web pages more responsive and interactive by reducing page refreshes or postbacks. It harnesses the power of client-side JavaScript and the XML HTTP object to provide these features.

Although AJAX is essentially a client-side technique, most of its real-world deployments call for server-side processing. Most commonly, the data manipulated by your web site will reside in some RDBMS on the server. To make AJAX really useful, you need an easy and robust way to deal with this server-side data. Fortunately, ASP.NET AJAX provides a sound infrastructure for doing just that. AJAX communication happens between your browser and the server over the Internet. Naturally, web services can play a significant role in data transport and overall communication between the client and the server. This article shows how ASP.NET AJAX can consume ASP.NET web services.

Software Requirements

All the examples in this article are developed using the RC build of ASP.NET AJAX that you can download from ajax.asp.net. Moreover, you need to have SQL Server 2005 (Express Edition will do) with the Northwind database installed. The examples use Visual Studio 2005 as the IDE.

Example Scenario

The example develops a web form that acts as a data entry page for an Employees table of the Northwind database. Using ASP.NET AJAX features, this data entry page will consume a web service that allows you to SELECT, INSERT, UPDATE, and DELETE employees.

Creating the Web Service

To begin with, create a new web site using Visual Studio 2005. Notice that installing ASP.NET AJAX adds project templates to the New Web Site dialog, including the “ASP.NET AJAX Enabled Web Site” template (see Figure 1).

Figure 1: The New Web Site Dialog with Added Templates

A web site created using the “ASP.NET AJAX Enabled Web Site” template is different from a normal web site in the following ways:

  • It has a web.config file with a lot of ASP.NET AJAX-specific configuration information.
  • It refers System.Web.Extensions assembly.

Of course, you can modify a normal web site to make it AJAX enabled, but this template simplifies your job.

Now that you have created a new web site, add a new web service to it and name it EmployeeService.asmx. The EmployeeService will contain five web methods (see Table 1).

Method Name Description
GetEmployees() Returns a list of employees from the Employees table. The list is returned in the form of an array of Employee objects.
GetEmployee() Accepts an EmployeeID and returns its details as an Employee object.
Insert() Adds a new employee to the Employees table.
Update() Updates an existing employee from the Employees table.
Delete() Deletes an existing employee from the Employees table.

Table 1. Web Methods in EmployeeService

The GetEmployees() and GetEmployee() methods return data in the form of Employee object(s). Therefore, you first need to create a class called Employee. Right-click the App_Code folder of your web site and choose “Add New Item…”. Add a new class called Employee. The following is the complete code that makes the Employee class:

public class Employee
{
   private int intEmployeeID;
   private string strFirstName;
   private string strLastName;

   public int EmployeeID
   {
      get
      {
         return intEmployeeID;
      }
      set
      {
         intEmployeeID = value;
      }
   }

   public string FirstName
   {
      get
      {
         return strFirstName;
      }
      set
      {
         strFirstName = value;
      }
   }

   public string LastName
   {
      get
      {
         return strLastName;
      }
      set
      {
         strLastName = value;
      }
   }
}

The Employee class declares three provate variables for storing employee ID, first name, and last name, respectively. The three variables are wrapped inside three public properties: EmployeeID, FirstName, and LastName.

Open the web.config file and add a <connectionStrings> section as follows:

<connectionStrings>
   <add name="connstr" connectionString=
        "data source=.\sqlexpress;
        initial catalog=northwind;
        integrated security=true"/>
</connectionStrings>

This stores a database connection string that points to the Northwind database. Make sure to change SQL Server name/IP and authentication details to match your environment.

Now, open EmployeeService.cs and add the following code:

private string strConn =
   "";

public EmployeeService()
{
   strConn = ConfigurationManager.ConnectionStrings["connstr"].
             ConnectionString;
}

The code uses the ConfigurationManager class to read the connection string from the config file and stores it in a class-level variable called strConn. This variable is used further by all the other web methods.

Now, add the GetEmployees web method as follows:

[WebMethod]
public Employee[] GetEmployees()
{
   SqlConnection cnn = new SqlConnection(strConn);
   cnn.Open();
   SqlCommand cmd            = new SqlCommand();
   cmd.Connection            = cnn;
   cmd.CommandText           = "select employeeid,firstname,
                                lastname from employees";
   SqlDataReader reader      = cmd.ExecuteReader();
   List<Employee> list = new List<Employee>();
   while (reader.Read())
   {
      Employee emp   = new Employee();
      emp.EmployeeID = reader.GetInt32(0);
      emp.FirstName  = reader.GetString(1);
      emp.LastName   = reader.GetString(2);
      list.Add(emp);
   }
   reader.Close();
   cnn.Close();
   return list.ToArray();
}

The code creates new SqlConnection and SqlCommand objects. It then executes a SELECT query and fetches EmployeeID, FirstName, and LastName columns from the Employees table. The results are retrieved as SqlDataReader instances. Then, a generic-based List of Employee objects is created. A while loop iterates through the SqlDataReader. With each iteration, a new Employee object is created and its EmployeeID, FirstName, and LastName properties are set. The Employee object then is added to the List. After the while loop completes, SqlDataReader and SqlConnection are closed. The return type of the GetEmployees() web method is an array of Employee objects. Hence, the generic List is converted into Employee array using the ToArray() method of the List class.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read