C# Web method is not calling in javascript

There are few rules for ajax to work with asp.net.

  • Your WebMethod should be public and static.
  • 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 in WebMethod and in data part of ajax.
  • Data passed from ajax should be in json string.For this you can use JSON.stringify or you will have to surround the values of parameter(s) in quotes.

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()

Leave a Comment