Ali Alhamaly Ali Alhamaly - 1 month ago 11
Ajax Question

Unknown web-method, trying to send json using AJAX

I'm trying to pass some data (parameter) from client side (html) to the server side (C# code-behind) to a method, this is done using AJAX in JSON format, but I'm getting the following error:


Unknown Web Method


my AJAX code is:

var jsonObj = { "sCriterion": sCriterion };
$.ajax({
type: "POST",
url: "NewToken.aspx/GetSelection",
data: jsonObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + JSON.stringify(XMLHttpRequest) + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert(data);
alert("We returned: " + result);
}
});


and this is my code-behind method:

[WebMethod]
private static string GetSelection(string selectedItem)
{

var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
var jsonObj = json.Serialize("proceeded");
return jsonObj;
}

Answer

The method should be public static to work. Not private !

[WebMethod]
public static string GetSelection(string selectedItem)
{

    var json = new JavaScriptSerializer();
    var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
    var jsonObj = json.Serialize("proceeded");
    return jsonObj;
}
Comments