Wednesday, March 7, 2012

Calling ASP.Net WebMethods using jQuery

Hey there world
Its a Wednesday afternoon and we want to do 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 a 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 plugin



    public static string Myfunction(string title, string desc)
            return "kuldeep";
        catch (Exception)

follwing are some another functionaly....!

(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); }
            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;
            error: function (response) {
                if (settings.debug) { alert("Error Calling Method \"" + settings.methodName + "\"\n\n+" + response.responseText); }
        return result;
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"
This snippet below calls the GetDate() WebMethod shown 
$.webMethod({ 'methodName': 'GetDate', 'parameters': { 'client': 3 },
                success: function (value) { alert(value); }
        public static string GetDate(int client)
            return string.Format("{0} says {1}", client, DateTime.Now.ToString("r"));