Search code examples
c#.netajaxpostwebmethod

webmethod isn't catching ajax POST


I'm trying to call a server side method with ajax. This is what I've got:

Client side:

function accept(thisButton) {
    $.ajax({
        type: "POST",
        url: "Default.aspx/editMaxUsers",
        data: '{param: "' + $(thisButton).prev().val() + '" }',
        contentType: "application/json: charset=utf-8",
        dataType: "json",
        success: function (result) { alert("successful" + result.d); }
    });
}

Server side:

[System.Web.Services.WebMethod]
public static string editMaxUsers(string maxUsers)
{
    return maxUsers;   //I also have a breakpoint here that isn't stopping the execute
}

When I check the calls with firebug I can see that the POST is being sent and looks fine. But Nothing seems to be happening on server side. What am I doing wrong?

EDIT: Don't know if it's relevant, but the url already contains some parameters. I've tried the following url: "Default.aspx/" + window.location.search + "editMaxUsers" but no success.


Solution

  • 1.Go to App_Start/RouteConfig and change

    settings.AutoRedirectMode = RedirectMode.Permanent;
    

    to

     settings.AutoRedirectMode = RedirectMode.Off;
    

    2.As @F11 said the paramter in the WebMethod and the key in the json object should be with the same name and what I strongly recommend is not to build json object manually. It is better to do:

    function accept(thisButton) {
     var data = {};
     data.maxUsers = $(thisButton).prev().val(); 
    $.ajax({
        type: "POST",
        url: "Default.aspx/editMaxUsers",
        data: JSON.stringify(data),
        contentType: "application/json: charset=utf-8",
        dataType: "json",
        success: function (result) { alert("successful" + result.d); }
    });
    }