Javascript – How to Call Code Behind Method from JavaScript

asp.netcjavascriptwebforms

I'm have few days reading and searching an answer for this question but I don't found.

I'm using this code

$('#Button1').click(function () {
            $.ajax({
                type: "POST",
                url: "/Default.aspx/ServerSideMethod",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                cache: false,
            })
            return false;
        });
        });

for try to call C# Method

[WebMethod]
 public void ServerSideMethod() {//Do something}

But I could not found any solution that work….

Best Answer

For it to work, ensure that the method location set in url is correct and that the method is public and static and that is has a [WebMethod] attribute added such as:

[WebMethod]
public static void doAll()
{
    //do something
}

if the url is "/Default.aspx/ServerSideMethod" then your method should look like this:

[WebMethod]
public static void ServerSideMethod()
{
    //do something
}