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.


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


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 ($) {    
        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 
                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

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

7 Responses to ASP.NET WebMethods with jQuery and AJAX

Leave a Reply

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