Location > Blog

Using jQuery AJAX and Page Methods with a ASP.NET WebService

I have recently started using the JQuery javascript library for a number a small projects. I have really enjoyed using jQuery, it makes javascript development really easy especially if you want to do some simple animations. There is a lot of good documentation that is easy to follow and a lot of plugins available, its worth a good look through before you make your own javascript application.

I got to thinking about Ajax and getting data out of an ASP.NET WebService. You can of course use ASP.NET Page Methods. But if you are already working with jQuery you may prefer to stick to using jQuery. You can trim down the size of your page because you won't need the ASP.NET AJAX client scripts.

Create an ASP.NET WebService

First we need to create an ASP.NET WebService. I opted to use a page with a WebMethod. I wanted to pass back a list of objects so I also created a simple class, here's the code. I have created two methods TestMethod and TestError. The first one demonstrates a successful Ajax request and the second when an error occurs on the server side as you may want to do some error handling. 

 
    [Serializable] 
    public class food 
    { 
        private string _name; 
 
        public string name 
        { 
            get { return _name; } 
            set { _name = value; } 
        } 
  
        public food() 
        { 
            _name = string.Empty; 
        } 
  
        public food(string name) 
        { 
            _name = name; 
        } 
    } 
 
    public partial class Test : Page 
    { 
        [WebMethod] 
        public static List<food> TestMethod() 
        { 
            List<food> items = new List<food>(); 
            items.Add(new food("bread")); 
            items.Add(new food("cheese")); 
            items.Add(new food("milk")); 
            items.Add(new food("eggs")); 
 
            return items; 
        } 
 
        [WebMethod] 
        public static void TestError() 
        { 
            throw new Exception("This is an error"); 
        } 
    } 
 

Client side javascript

Next we need the client side javascript. In this example I have included a jQuery example and ASP.NET Page Method example so we can see the two ways of doing this. For the jQuery method you need to include the jQuery javascript library in your page and for the ASP.NET Page Methods example you need to have a ScriptManager on the page and set the property EnablePageMethods="true". This includes a extra bit of client side code that enables you to call the PageMethods.

Extending jQuery with a Ajax wrapper method

 
    $.pageMethod = function(url, data, callback) { 
        if(url.indexOf("/")==-1) 
        { 
            url = location.pathname + "/" + url 
        } 
        if (jQuery.isFunction(data)){ 
            callback = data; 
            data = "{}"; 
        } 
        $.ajax({ 
            type: "POST"
            url: url, 
            data: data
            contentType: "application/json; charset=utf-8"
            dataType: "json"
            success: callback 
        }); 
    }; 
 

Calling the WebMethod

You can see below aspNetPageMethod and jQueryPageMethod functions, both call the server side WebMethod called TestMethod in both examples there is a function that is called if the request is successful or if an error occurred. You  can generate an error by changing the call to the TestError method.

 
    function aspNetPageMethod() 
    { 
        PageMethods.TestMethod(OnSucceeded, OnFailed); 
    } 
 
    function jQueryPageMethod() 
    { 
        $(document).ajaxError(jQueryFailed); 
        $.pageMethod("TestMethod", jQuerySucceeded); 
    } 
  

There are some more javascript functions required to handle the success and failure states.

 
    function getMessage(items){ 
        var items = jQuery.makeArray(items) 
        var message = items.length + " item/s returned:"
        for(var i=0;i<items.length;i++){ 
            message = message + "\n" + (i + 1) + ") " + items[i].name; 
        } 
        return message; 
    } 
 
    function OnSucceeded(result, userContext, methodName) { 
        alert(getMessage(result));  
    } 
 
    function OnFailed(error, userContext, methodName) { 
       alert(error.get_message()); 
    } 
 
    function jQuerySucceeded(result) { 
        alert(getMessage(result));  
    } 
 
    function jQueryFailed(event, XMLHttpRequest, ajaxOptions, thrownError) { 
       alert(eval("("+XMLHttpRequest.responseText+")").Message); 
    } 
 

Calling the methods

Last call the aspNetPageMethod and jQueryPageMethod functions a click on a link is fine for this example. Clicking on either link results in the same result. You can see the formated list returned from the server side call TestMethod.


Serialized List of objects

Using FIreBug you can view the Json serilized List<food> class returned from the server, the Json is created for you by the server. From your client side javascript you can access this like any other Json object.



So this is a very efficient way to make a call to a ASP.NET WebService if you use jQuery or ASP.NET AJAX PageMethods. I can see a lot of areas where this will be useful.

You may be interested in my follow up article Client Side Binding Using Ajax Page Methods and jQuery


Saturday November 29 2008 11:54 a.m.