Consuming an ASP.NET web service or page method using jQuery


The following is a dummy ASP .NET web service. Please note that this service is adorned with the ScriptService attribute that makes it available to JavaScript clients.

Listing 2: A Dummy web service
  1. [WebService(Namespace = "http://tempuri.org/")]  
  2. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  3. [System.Web.Script.Services.ScriptService]  
  4. public class dummyWebservice : System.Web.Services.WebService  
  5. {  
  6.   [WebMethod()]  
  7. public string HelloToYou(string name)  
  8.   {  
  9. return "Hello " + name;  
  10.   }  
  11.   [WebMethod()]  
  12. public string sayHello()  
  13.   {  
  14. return "hello ";  
  15.   }    

For example, we can call a specific web method in a web service as such.

Listing 4: JQuery .ajax command
  1.   $.ajax({  
  2.   type: "POST",  
  3.   contentType: "application/json; charset=utf-8",  
  4.   url: "WebService.asmx/WebMethodName",  
  5.   data: "{}",  
  6.   dataType: "json"
  7. }); 

Two things are worth noting in the above JQuery AJAX call. First, we must specify the contentType’s value as application/json; charset=utf-8, and the dataType as json; second, to make a GET request, we leave the data value as empty.

So put it together, the following code demonstrates how we would use JQuery to call the web service we created above.

Listing 5: Calling a web service using jQuery
  1. <%@ Page Language="C#" %>
  2. <%@ Import Namespace="System.Web.Services" %>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   
  4. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
  5. <html >
  6. <head id="Head1" runat="server">
  7. <title>ASP.NET AJAX Web Services: Web Service Sample Page</title>
  8. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jQuery/1.2.6/jQuery.min.js"&gt;
  9. </script>
  10. <script type="text/javascript">
  11.       $(document).ready(function() {  
  12.          $("#sayHelloButton").click(function(event){  
  13.              $.ajax({  
  14.                  type: "POST",  
  15.                  url: "dummyWebsevice.asmx/HelloToYou",  
  16.                  data: "{‘name’: ‘" + $(‘#name’).val() + "’}",  
  17.                  contentType: "application/json; charset=utf-8",  
  18.                  dataType: "json",  
  19.                  success: function(msg) {  
  20.                      AjaxSucceeded(msg);  
  21.                  },  
  22.                  error: AjaxFailed  
  23.              });  
  24.          });  
  25.      });  
  26.           function AjaxSucceeded(result) {  
  27.               alert(result.d);  
  28.           }  
  29.           function AjaxFailed(result) {  
  30.               alert(result.status + ‘ ‘ + result.statusText);  
  31.           }    
  32. </script>
  33. </head>
  34. <body>
  35. <form id="form1" runat="server">
  36. <h1> Calling ASP.NET AJAX Web Services with jQuery </h1>
  37.      Enter your name:   
  38. <input id="name" />
  39. <br />
  40. <input id="sayHelloButton" value="Say Hello"
  41. type="button" />
  42. </form>
  43. </body>
  44. </html>

Calling an ASP .NET page method

Listing 6: A dummy hello world page method

  1. [WebMethod()]  
  2. public static string sayHello()  
  3. {  
  4. return "hello ";  
  5. }   

Please note that page methods must be declared as static, meaning a page method is completely self-contained, and no page controls are accessible through the page method. For example, if you have a textbox on the web form, there is no way the page method can get or set its value. Consequently any changes with regards to the controls have no affect on the page method. It is stateless and it does not carry any of the view-state data typically carries around by an asp .NET page.

We use the same jQuery command $.ajax to call a page method, as shown in the following example.

  1. <script type="text/javascript">  
  2.       $(document).ready(function() {  
  3.           $.ajax({  
  4.               type: "POST",  
  5.               url: "pagemethod.aspx/sayHello",  
  6.               contentType: "application/json; charset=utf-8",  
  7.               data: "{}",  
  8.               dataType: "json",  
  9.               success: AjaxSucceeded,  
  10.               error: AjaxFailed  
  11.           });   
  12.     });  
  13. function AjaxSucceeded(result) {  
  14.           alert(result.d);  
  15.       }  
  16. function AjaxFailed(result) {  
  17.           alert(result.status + ‘ ‘ + result.statusText);  
  18.       }    
  19.   </script>   

For more info please visit Xun Ding’s excellent article Using jQuery with ASP .NET

15 thoughts on “Consuming an ASP.NET web service or page method using jQuery

  1. Hi,Great to see such snippets.
    Can you please forward any sample site for this.

    Have you added refference of web service in existing site. how to specify url (can i specify full url) and how to pass more than one parameter for data{}.

    my sample code
    var passingArguments = {
    Username:$(‘#name’).val(),
    Password:$(‘#txtPassword’).val(),
    LoginUserID:$(‘#txtLoginId’).val()
    }
    $.ajax({
    type: “POST”,
    url: “http://localhost/JQ/Service.asmx/GetValidate”,
    data:JSON.stringify(passingArguments),
    contentType: “application/json; charset=utf-8”,
    dataType: “json”,

    Now how i can get returned values. bcoz on returned values i have to made some navigation and error handling.

    Please reply.

  2. I found that it works even if you don’t specific the json datatype, as long as the contentType attribute is set.

  3. For Some reason using your code this appears to always be going to ajax failed with status 200 and statustext ok confused :S

  4. Pingback: [RESOLVED]can we pass database values in json | ASP Questions & Answers

Leave a comment