Johan Hjalmarsson
Johan Hjalmarsson

Reputation: 3493

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.

Upvotes: 0

Views: 145

Answers (2)

Koce
Koce

Reputation: 116

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); }
});
}

Upvotes: 0

F11
F11

Reputation: 3806

The parameters of your WebMethod need to match the parameter name you are passing in. Change

data: '{param: "' + $(thisButton).prev().val() + '" }',

to

data: '{maxUsers: "' + $(thisButton).prev().val() + '" }',

Upvotes: 3

Related Questions