Search code examples
c#jqueryasp.netajaxwebmethod

Can't get ajax call with parameters to hit my C# function


Ajax:

var test = "test";

$.ajax(
{
  type: "POST",
  url: "project/function",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  data: { input: test },
  success: function (response) {
    $("#lblMsg").text(response.d);
  },
  failure: function (response) {
    alert(response.d);
  }
});

C# function:

[WebMethod]
public void function(string input)
{
}

The connection is made successfully when I don't include a parameter. I have tried different single and double quote permutations of the 'data' portion of the ajax call, to no avail.

I have also tried setting the dataType to "text" with similar results.

What am I missing?


Solution

  • I would suggest that you shouldn't send your data as JSON. Just remove the

    contentType: "application/json; charset=utf-8"
    

    and jQuery will serialise the data into normal url-encoded form data format, which is what the WebMethod is expecting.