Vincent Leung .NET Tech Clips

The latest tech clips from the .NET community

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

About these ads

February 10, 2009 - Posted by | jQuery

13 Comments »

  1. How does the JQuery.Ajax data option change when the web service requires more than one parameter?

    Comment by Joel | July 22, 2009 | Reply

    • Just change it to this {‘param’:'value’,'param1′:’value1′}

      Comment by Sifiso Shezi | April 7, 2011 | Reply

  2. Thanks for this tutorial. I liked it very much.

    Comment by rana | December 24, 2009 | Reply

  3. 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.

    Comment by Kapil | January 15, 2010 | Reply

  4. Hai Your code was very useful…………….

    Comment by Pratap | February 26, 2010 | Reply

  5. what if webservice is located on another subdomain? tried it and didn’t work

    Comment by Alex | May 12, 2010 | Reply

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

    Comment by Jason | July 27, 2010 | Reply

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

    Comment by Craig | August 9, 2011 | Reply

  8. how to call the static method in webservice.is this possible?

    Comment by karthick | September 29, 2011 | Reply

  9. i am not getting any result?

    Comment by karthick | September 29, 2011 | Reply

  10. This doesn’t work for me. Same issue as @Craig above. The web service is called successfully, but nothing is returned.

    Comment by Ross | October 19, 2011 | Reply

  11. it is not working it gives only error msg

    Comment by sweetymathur | April 6, 2013 | Reply

  12. Hmm is anyone else experiencing problems with the pictures on this blog loading?

    I’m trying to determine if its a problem on my end or if it’s
    the blog. Any suggestions would be greatly appreciated.

    Comment by Phen375 Reality | May 10, 2013 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: