Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Calling ASP.NET WebMethods using jQuery

0.00/5 (No votes)
21 Nov 2011 1  
How to call ASP.NET WebMethods using jQuery

It's a Friday afternoon and you want to write some hot and funky code using WebMethods and AJAX but you then encounter the problems and excess baggage of Microsoft's Ajax Implementation. Why not use jQuery? Well, with this neat code snippet below, you can now call a WebMethod in an ASP.NET page without all the baggage of ASP.NET AJAX Client Script libraries! All you need is ASP.NET, JQuery and a little JSON magic supplied by the jQuery-JSON library plug in.

JavaScript
(function ($) {
    $.webMethod = function (options) {
        var settings = $.extend({
            'methodName': '',
            'async': false,
            'cache': false,
            timeout: 30000,
            debug: false,
            'parameters': {},
            success: function (response) { },
            error: function (response) { }
        }, options);         var parameterjson = "{}";
        var result = null;
        if (settings.parameters != null) { parameterjson = $.toJSON(settings.parameters); }
        $.ajax({
            type: "POST",
            url: location.pathname + "/" + settings.methodName,
            data: parameterjson,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: settings.async,
            cache: settings.cache,
            timeout: settings.timeout,
            success: function (value) {
                result = value.d;
                settings.success(result);
            },
            error: function (response) {
                settings.error(response);
                if (settings.debug) { alert("Error Calling Method \"" + 
                   settings.methodName + "\"\n\n+" + response.responseText); }
            }
        });
        return result;
    };
})(jQuery);

Simply pasting this code into a JavaScript file and referencing it after your favourite version of the jQuery Library creates a new jQuery method called "webMethod".

The following parameters are available:

methodName

Denotes the name of the Server-side method to call.

async

Determines if jQuery is to wait for the Server side process to finish.

cache

Determine if jQuery will append caching headers to the request.

timeout

Timeout to wait for a server response.

debug

When set to true, a JavaScript alert box is shown if any runtime error occurs on the server.

parameters

An Object containing any parameters to pass to the server-side method.

success

A Callback function which is run when the request completes successfully. The results from the server side function are passed as a parameter.

error

A Callback function which runs when the request fails in some way. The standard Error object is passed as a parameter.

This snippet below calls the GetDate() WebMethod shown:

JavaScript
$.webMethod({ 'methodName': 'GetDate', 'parameters': { 'client': 3 },
                success: function (value) { alert(value); }
            });

And the C# Codebehind that's being called by this function:

JavaScript
[WebMethod]
        public static string GetDate(int client)
        {
            return string.Format("{0} says {1}", 
            client, DateTime.Now.ToString("r"));
        }

Note the all-important [WebMethod] declaration that tells ASP.NET to work its Server-Side ASP.NET AJAX Magic.

Simples! And all in a few lines of code - a much smaller footprint.

Thanks to the jQuery-JSON plug in here for the excellent JSON Conversion routines.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here