Using PageMethods with jQuery

TheVillageIdiot picture TheVillageIdiot · May 22, 2009 · Viewed 7.7k times · Source

Simply put I want to call public static methods decorated with WebMethod attribute inside my code-behind C# file from jquery.ajax to get some json and other simple stuff (in different functions). But instead I'm getting whole page :'(

I'm not using asp.net AJAX though I'm developing for .NET 3.5 framework and using VS 2008. (There are some restrictions from client)

Please let me know if I can use page-methods with using asp.net ajax or If not what is other simple solution?

Answer

TheVillageIdiot picture TheVillageIdiot · Jun 8, 2009

After much deliberations I found the problem. I was using jquery's editable plugin. This was source of the problem. When jeditable calls jquery's ajax it sets ajax options like this:

    var ajaxoptions = {
        type: 'POST',
        data: submitdata,
        url: settings.target,
        success: function(result, status) {
            if (ajaxoptions.dataType == 'html') {
                $(self).html(result);
            }
            self.editing = false;
            callback.apply(self, [result, settings]);
            if (!$.trim($(self).html())) {
                $(self).html(settings.placeholder);
            }
        },
        error: function(xhr, status, error) {
            onerror.apply(form, [settings, self, xhr]);
        }
    };

so it was sending the things as simple html and to use this with page methods we need to setup the things so that it sends as json. So we need to add something to the settings like this:

    var ajaxoptions = {
        type: 'POST',
        data: submitdata,
        url: settings.target,
        dataType: 'json', //Data Type
        contentType: 'application/json; charset=utf-8', //Content Type
       //....other settings
    };

So I put two new properties in settings dataType and contentType and changed above to this:

    var ajaxoptions = {
        type: 'POST',
        data: submitdata,
        url: settings.target,
        dataType: settings.dataType,
        contentType: settings.contentType,
       //....other settings
    };

Now another problem arised :( it was sending data (from submitdata property) as normal query-string which asp.net does not accept with json requests. So I had to use jquery's json plugin and change the way data is sent in ajax using following test on dataType:

    if (settings.dataType == "json") {
        if ($.toJSON) {
            submitdata = $.toJSON(submitdata); 
        }
    }

and it works like breeze!!!