Using JQuery, AJAX, JSON and ASP.NET Web Services

Waqas Anwar
06 November 2010
101021 Views

Due to the latest paradigm shift in web development, more and more websites are loading and displaying all types of dynamic contents on the web pages. Web 2.0 based websites such as Gmail. Facebook and Twitter have not only changed the user’s expectations but also forced developers to learn more dynamic and exciting ways to build web applications. Client side web technologies like AJAX, XHTML, DOM, JavaScript and JQuery are now mandatory ingredients of every web developer resume. In my previous tutorial, I have shown you how you can call ASP.NET web services using JQuery AJAX capabilities. In this tutorial, I will show you how you can pass parameters to web services and how you can use JSON data returned from web services to display dynamic contents on web page.

Before you start reading this tutorial, I will recommend you to read my previous tutorial Calling ASP.NET Web Services using JQuery AJAX to have some basic understanding of JSON and JQuery AJAX capabilities. If you are new to JQuery then I will recommend you to read my first tutorial Introducing JQuery for ASP.NET Developers before reading this tutorial.

Create a new ASP.NET website in the visual studio and add following Employee.cs class in App_Code folder of your project. I will be using this class from the web service to return the list of Employee class objects to the clients.

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }
}

Next, add an ASP.NET web service EmployeeWebService.asmx in the project by using Add New Item dialog box. The complete web service code is shown below:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class EmployeeWebService : System.Web.Services.WebService {

    List<Employee> list = new List<Employee>();

    public EmployeeWebService () {

        //Uncomment the following line if using designed components
        //InitializeComponent();

        list.Add(new Employee { Id = 1, Name = "Peter", Salary = 22000 });
        list.Add(new Employee { Id = 2, Name = "Mark", Salary = 24000 });
        list.Add(new Employee { Id = 3, Name = "James", Salary = 28000 });
        list.Add(new Employee { Id = 4, Name = "Simon", Salary = 29000 });
        list.Add(new Employee { Id = 5, Name = "David", Salary = 19000 });

    }

    [WebMethod]
    public List<Employee> GetAllEmployees() { 
        return list;
    }


    [WebMethod]
    public Employee GetEmployeeDetails(string employeeId)
    {
        int empId = Int32.Parse(employeeId);
        Employee emp = list.Single( e => e.Id == empId);
        return emp;
    }

}

In start, the web service declares a list of Employee objects which I will be using to store employee objects for this tutorial.
List<Employee> list = new List<Employee>();
I have added five employee objects to the list in the constructor of the web service. I am using this approach only for simplifying this tutorial as in a real world application these records are normally stored in the database.
list.Add(new Employee { Id = 1, Name = "Peter", Salary = 22000 });
list.Add(new Employee { Id = 2, Name = "Mark", Salary = 24000 });
list.Add(new Employee { Id = 3, Name = "James", Salary = 28000 });
list.Add(new Employee { Id = 4, Name = "Simon", Salary = 29000 });
list.Add(new Employee { Id = 5, Name = "David", Salary = 19000 });

A web method GetAllEmployees returns the list of employees to the clients.

[WebMethod]
public List GetAllEmployees()
{
   return list;
}

Another simple web method GetEmployeeDetails will filter and return a single Employee object based on employee id.
[WebMethod]
public Employee GetEmployeeDetails(string employeeId)
{
   int empId = Int32.Parse(employeeId);
   Employee emp = list.Single( e => e.Id == empId);
   return emp;
}

Next add the following code in your web page in HTML source. It has a DropDownList to display all employees and an HTML table to display single employee details.
<form id="form1" runat="server">
   
Select Employee:
   
   <asp:DropDownList ID="DropDownList1" runat="server" Width="150">
      <asp:ListItem Text="Select" Value="-1" />
   </asp:DropDownList>

   
   <br />
   <br />
   
   <table style="border: solid 1px black; width: 300px; display: none; background-color: #f3f3f3"
      cellpadding="4" cellspacing="0" id="outputTable">
      <tr>
         <td>Employee ID:</td>
         <td><span id="spnEmployeeId" /></td>
      </tr>
      <tr>
         <td>Employee Name:</td>
         <td><span id="spnEmployeeName" /></td>
      </tr>
      <tr>
         <td>Salary:</td>
         <td><span id="spnSalary" /></td>
      </tr>
   </table>

</form>

Before staring JQuery AJAX code make sure you have JQuery file available in the scripts folder of your website, and you have added file reference in the page <head> element.
<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
Next add a JavaScript code block and typical JQuery ready function to get things started when the document is ready and DOM tree is loaded by the browser. The first statement is a call to another JavaScript function GetAllEmployees which is declared just after ready function. This function will call GetAllEmployees web service method, and then it will populate the DropDownList control from the JSON data returned from the web service method. Next the DropDownList change event function handler is defined, which first gets the selected employee id from the DropDownList using JQuery val method and then pass that employee id to another JavaScript function GetEmlployeeDetails which will retrieve details of that particular employee by calling web service GetEmployeeDetails method and then will display details in HTML table.
<script type="text/javascript">

   $(document).ready(function () {

      // Load Employees
      GetAllEmployees();

      var DropDownList1 = $("#DropDownList1");

      DropDownList1.change(function (e) {

         var employeeId = DropDownList1.val();
         if (employeeId != -1) {

            // Get Employee Details
            GetEmployeeDetails(employeeId);

         } else {

            $("#outputTable").hide();
         }

      });
   });

   function GetAllEmployees() {
      // JQuery AJAX Code Here
   }

   function GetEmployeeDetails(employeeId) {
      // JQuery AJAX Code Here
   }


</script>

As you can see in the above code, I didn’t define the GetAllEmployees and GetEmployeeDetails functions so that you can focus on ready function implementation and can understand more easily what is going on in JQuery ready function. To complete this tutorial, I need to show you the code required inside the above two functions to call web services methods and to update controls and user interface elements. Following is the implementation of GetAllEmployees function:
function GetAllEmployees()
{
   var DropDownList1 = $("#DropDownList1");
   $.ajax({
      type: "POST",
      url: "EmployeeWebService.asmx/GetAllEmployees",
      data: "{}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (response) {

         var Employees = response.d;
         $.each(Employees, function (index, employee) {
            DropDownList1.append('<option value="' + employee.Id + '">' + employee.Name + '</option>');
         });

      },
      failure: function (msg) {
         alert(msg);
      }
   });
}

In the above code snippet, JQuery ajax() method is used to send AJAX request to ASP.NET web service method GetAllEmployees. From the parameters, you can easily guess the service method url, request type (POST) and data type (JSON). If you are not familiar with the ajax() method parameters, I will recommend you to read my tutorial Calling ASP.NET Web Services using JQuery AJAX for more detailed understanding of the ajax() method and JSON.

Inside the success function handler of ajax() method, I have used JQuery each() method to loop through all the employees I received in JSON response (response.d) and I appended the HTML elements inside DropDownList to display all employees. If you will build and test your page in the browser you will see DropDownList populate with employee names as shown in the following figure. You can also see the JSON response in FireBug just below to the DropDownList.


JQuery AJAX JSON Response

The following is the code required for the GetEmployeeDetails function. The code is almost similar to the GetAllEmployees function as it is also using JQuery ajax() method to call web service method but there are two differences. First, I am passing employee id as a parameter in JSON format using the data option of JQuery ajax() method. Second, inside success method I am not using any loop to iterate employees as there is only one employee to receive from the web service method. Note the Employee class properties Id, Name and Salary are used to display values inside span elements declared in HTML table above.
function GetEmployeeDetails(employeeId)
{
   $.ajax({
      type: "POST",
      url: "EmployeeWebService.asmx/GetEmployeeDetails",
      data: "{'employeeId':'" + employeeId + "'}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (response)
      {
         var Employee = response.d;
         $("#spnEmployeeId").html(Employee.Id);
         $("#spnEmployeeName").html(Employee.Name);
         $("#spnSalary").html(Employee.Salary);
         $("#outputTable").show();

      },
      failure: function (msg)
      {
         alert(msg);
      }
   });
}

That’s all we need to call web service methods using JQuery AJAX and to display single or multiple records coming from web service method in JSON format. Build and run your web page, and you will see output similar to following figure:


JQuery AJAX JSON Response


I hope, you have found this tutorial useful, and you will start using the above mentioned techniques in your web applications to give your end users better and responsive user interfaces. Keep visiting my website in the future for more tutorials.