Search code examples
jqueryasp.netajaxwebmethod

Why can I not access my webmethod from AJAX?


I'm trying to make an AJAX call to a webmethod in my asp.net page and I cannot seem to pass the data over.

This is my AJAX call

$.ajax({
    type: "GET",
    url: "EditView.aspx/GetAllKeywords",
    data: JSON.stringify({
        keywordIds: ['1', '2']
    }),
    contentType: "application/json; charset=utf-8",
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    complete: function(jqXHR, status) {
        alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
    }
});

and this is my WebMethod

[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string GetAllKeywords(string[] keywordIds)
{
    return "it worked";
}

Everytime I run it, I keep getting this error

"Invalid web service call, missing value for parameter: \u0027keywordIds\u0027."

which indicates to me, it's not able to match my data from my ajax call to the parameter in my webmethod. What am I doing wrong?


Solution

  • I quickly created a sample application and observed that you should be using POST instead of GET. When I applied the following settings, I was able to hit the GetAllKeywords method and get the response back successfully.

    SCRIPT

    <script>
            $.ajax({
                type: "POST",
                url: "WebForm1.aspx/GetAllKeywords",
                data: JSON.stringify({
                    keywordIds: ['1', '2']
                }),
                contentType: "application/json; charset=utf-8",
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
                },
                complete: function (jqXHR, status) {
                    alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
                }
            });
        </script>
    

    C#

    Use POST instead of GET

     [WebMethod(EnableSession = true)]
     [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
     public static string GetAllKeywords(string[] keywordIds)
     {
        return "it worked";
     }
    

    DEBUG

    Snapshot from debug mode,

    enter image description here