There are few rules for ajax to work with asp.net.
- Your WebMethod should be
public
andstatic
.- If your WebMethod expects some parameter(s) than these parameter(s) must be passed as
data
in ajax.- Name of parameter(s) should be
same
inWebMethod
and indata
part of ajax.- Data passed from ajax should be in
json string
.For this you can useJSON.stringify
or you will have to surround thevalues
of parameter(s) inquotes
.
Please check the below sample ajax call
function CallAjax()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/CallAjax",
data: JSON.stringify({ name: "Mairaj", value: "12" }),
dataType: "json",
async: false,
success: function (data) {
//your code
},
error: function (err) {
alert(err.responseText);
}
});
}
[WebMethod]
public static List<string> CallAjax(string name,int value)
{
List<string> list = new List<string>();
try
{
list.Add("Mairaj");
list.Add("Ahmad");
list.Add("Minhas");
}
catch (Exception ex)
{
}
return list;
}
EDIT
If you use GET
in ajax than you need to enable your webmethod to be called from GET
request. Add [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
on top of WebMetod
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static int ItemCount()