ASP.NET WebMethods with jQuery and AJAX

I haven’t updated this blog in a long, long time, but today I was working on something interesting and thought I should write it down before I forget.

I was working on an ASP.NET application and needed to perform an AJAX request, I could have used the Microsoft AJAX framework, but frankly I don’t like it. Using the Microsoft ScriptManager element pulls in a lot of extra bloat that really isn’t necessary and the project was already using jQuery for animations. 
ASP provides these things called WebMethods (You’d probably be familiar with these if you’ve ever implemented a ASP.NET WebService), basically they’re a server side function that can be invoked similar to that of a REST API, a la Flickr.

Basically in your ASP.NET page code-behind file you just need to add a static / shared method that is decorated with a special WebMethod attribute.

VB.NET

<System.Web.Services.WebMethod()> _
Public Shared Function HelloWorld(ByVal name As String) As String
    Return String.Format("Hello world, meet {0}", name)
End Function

C#

[System.Web.Services.WebMethod]
public static string HelloWorld(string name)
{
    return string.Format("Hello world, meet {0}", name);
}

On the front end, I wrote a jQuery extension to consume these methods. This just needs to be included anywhere on the page.

jQuery(function ($) {    
    $.extend({
        webMethod: function (method, data, onSuccess, onFail) {
            var loc = window.location.href.split('?')[0];
            if (loc.substr(loc.length - 1, 1) == "/")
                loc = loc + "Default.aspx";
 
            // Serialize the data object with no whitespace 
            // (.NET requirement)
            var pairs = [];
            for (var i in data) {
                pairs.push(i + ':' + data[i]);
            }
            data = '{' + pairs.join(',') + '}';
 
            // Perform the post operation 
            $.ajax({
                type: "POST"
                , url: loc + "/" + method
                , 'data': data
                , contentType: "application/json; charset=utf-8"
                , dataType: "json"
                , success: onSuccess
                , error: function (jqXHR, textStatus, errorThrown) {
                    // The .NET error and stacktrace is hidden 
                    // inside the XMLHttpRequest response
                    if($.isFunction(onFail))
                        onFail($.parseJSON(jqXHR.response));
                }
            });
        }
    });
});

To invoke the above you’d do something like:

jQuery.webMethod('HelloWorld', { 
    name: 'Trent'
}, onSuccess, onFailure);
 
function onSuccess(data) {
    // The response from the function is in the attribute d
    alert(data.d);
}
 
function onFailure(data) {
    alert(data.Message + "\n" + data.StackTrace);
}

This will perform an AJAX request to the server and invoke your server side WebMethod.
If anyone has any comments or feedback, please let me know.

This entry was posted in .NET, jQuery. Bookmark the permalink.

4 Responses to ASP.NET WebMethods with jQuery and AJAX

  1. Troy Scheffel says:

    Very nice example! Easy-to-read, simple yet functional, and an elegant solution. Thanks!

  2. tony says:

    mate you forgot to add ‘static’ :
    public string HelloWorld(string name){…}

    should be:
    public static string HelloWorld(string name){…}

  3. shane says:

    In your C# example, you don’t declare the method as ‘static’. Also, I couldn’t get this to work. I received a 401 Unauthorzied – {“Message”:”Authentication failed.”,”StackTrace”:null,”ExceptionType”:”System.InvalidOperationException”}

    Any ideas why?

  4. mia says:

    very good example! Exactly what i was looking for! Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>