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

You are currently viewing Using JQuery, AJAX, JSON and ASP.NET Web Services

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.

READ ALSO:  Using Checkbox in ASP.NET GridView Control

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.

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 IdName 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:

READ ALSO:  Understanding ASP.NET AJAX UpdatePanel

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.

This Post Has 27 Comments

  1. richard

    If the Dropdownlist is not showing You could add the ‘ScriptServices’ into the web service as below.

    [WebService(Namespace = “http://tempuri.org/“)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]

  2. swapnil

    DROPDOWNLIST NOT SHOWING NAMES OF EMPLOYEEES

  3. Mehtab

    Thanks
    great job
    very use full to beginner just like me thanks again

  4. manimaan

    I am using external webservice ..its located in external service How can I give url
    $.ajax({
    type: “POST”,
    url: “IPadress/EmployeeWebService.asmx/GetEmployeeDetails”,

    is this correct

  5. verma

    nice works

  6. Dmitriy

    Thanks!!! Thanks!!! Thanks!!!

  7. Ujjwal Das

    Nice Post!! But I was trying dis similar method with phonegap and calling it in similar manner. But neither I get any error nor any data. What could be the reason? Also my web services has Content-Type: text/xml; charset=utf-8 so does it matter??

  8. Patrick

    This post is really helpful. Keep on doing your stuff its helping out big time.

  9. hitesh kumar

    sir your tutorial was awesome. this is really a great and best article especilly me, i m new for jquery and ajax. it really helps a lot.thanks, please keep writing.

  10. jone

    hi, I have read your article. You have explain the process well, but still i have a question. You know, when we use webservice, the service are always on the remote service mechine. It means that we will use the jQuery crossing domain. In this situation, I failed. Can you help me?

  11. Martinez

    I implemented two identical projects like yours. One was website, the other was web application. It works in website but it doesnt in web application.

    How to correct this issue?

  12. Stuart

    Great article, just need to point out one thing. You need to code your dropdownlist like so..

    <asp:dropdownlist id=”DropDownList1″ runat=”server” width=”150″ clientidmode=”Static”>
    <asp:listitem text=”Select” value=”-1″/>
    </asp:dropdownlist>

  13. undo

    Nice man!

  14. Pradeep

    Excelent

  15. Pradeep

    Excellent Article..

  16. V123

    Wonderful it helps me lot to get things started.
    Thanks a million.

  17. Soan

    Good article. Can you also show how we can receive a JSON object in asp.net web service, process the data and then return back some data again in JSON format?

    I am using visual studio 2010 express. Also, i want to use this asp.net web service in an Android application.

  18. Dhakchina

    It is really very excellent. I made a mistake in calling the JQuery, and was searching for the right way of making the call.

    Your explanation not only is very clean, but also teaches highly professional way of development.

    Thanks.

  19. Umair Aslamb

    Awesome effort , real time usage of jquery , json with asp.net webservice.

  20. laiho

    exellent

  21. Mani M

    Being an beginner, can able to understand. Very useful. thanks.

  22. Umair Aslam

    Awesome post , i normally using string builder or .net json class to build response in server page , but doing like this , as you did using webservice and list that is too awesome and time saving plus super fast i tried it and did some experiments found it more better
    Great Work keep it

  23. sudarshana

    HI,
    i saw the article which you posted.but i have a doubt,in place of URL:webservice/Getmethod.where we use to connect web service ,but in that article in the place of URL:data.xml….it shows like that.so how to connect the web service in jquery.

  24. sudarshana

    HI,
    Your tutorial were awesome…but can u help me out…how to call xml file from jquery using web services…
    thanks a lot.waiting for your reply

  25. Abelardo Duarte

    Great article, you are the man

  26. Craig

    Excellent article, thanks for posting it! You gave me an idea to use divs instead of a listview. So much thinner!

  27. Muhammad Naeem

    who Sir, this is really a great and best article, it really helps a lot.
    thanks, plz keep writing 😉

Leave a Reply