简体   繁体   中英

ASP.NET 3.5 calling [WebMethod] with AJAX - 500 Error

I have a Web Site Project (ASP.NET 3.5).

One of the methods is in Search.aspx.cs looks like this. This is a method I am trying to call so I can return some data to Ajax call:

    [WebMethod]
    public static string TestMethod(string param)
    {
        return "It worked";
    }

Having difficulty calling the above method from client side button click from inside the Search.aspx page :

<form runat="server" id="mainForm" class="form-horizontal">
<input id="addButton" type="button" value="Add" />
</form>

<script>
$('#addButton').click(function () {
            $.ajax({
                type: "GET",
                url: "Search.aspx/TestMethod",
                data: "{}",
                contentType: "application/json",
                dataType: "json",
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
                },
                success: function (result) {
                    alert("We returned: " + result);
                }
            });
        });

</script>

Here is the screen showing alert box from error ajax function.

在此处输入图片说明

Here is another from Firefox debugger:

在此处输入图片说明

Here is a screenshot with a complete error from Firefox debugger:

在此处输入图片说明

Your method expects to receive a parameter...

change your method to this:

[WebMethod]
public static string TestMethod()
{
    return "It worked";
}

Or change your js to this (you have to use POST type):

<script>
$('#addButton').click(function () {
            $.ajax({
                type: "POST",
                url: "Search.aspx/TestMethod",
                data: JSON.stringify({ "param" : "anything"}),
                contentType: "application/json",
                dataType: "json",
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
                },
                success: function (result) {
                    alert("We returned: " + result);
                }
            });
        });

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM