简体   繁体   中英

ASP.NET webmethod get ajax with parameters

I have a webmethod like this:

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string Name, int? Age)
{
    return "returned value";
}

And the ajax call :

$.ajax({
  type: "GET",
  url: "form.aspx/test",
  data: {'Name': "n1", 'Age': 30},
  contentType: "application/json; charset=utf-8",
  success: function (data) {
    console.log(data);
  }
});


Without parameters/data it works, but when I try to pass some parameters I get this error:

GET http://localhost:55410/test.aspx/test?Name=n1&Age=30
500 (Internal Server Error)


I think this's the detailed exception:

System.ArgumentException: Unknown web method form.
Parameter name: methodName

You need to pass an object instead of a string, and put quotes around n1 to make it a string:

$.ajax({
  type: "GET",
  url: "test.aspx/test",
  data: {'Name': 'n1', 'Age': 30},  // remove quotes & add quotes to n1
  contentType: "application/json; charset=utf-8",
  success: function (data) {
    console.log(data);
  }
});

If you want to pass parameters with url you dont need to use data property at all: Just pass them in the url itself like below:

 $.ajax({
  type: "GET",
  url: "form.aspx/test?name=" + yourStringVariabel + "&age=" + yourAgeVariabel,
  contentType: "application/json; charset=utf-8",
  success: function (data) {
    console.log(data);
  }
});

Try with a post and see if it works:

 $.ajax({
  type: "POST",
  url: "form.aspx/test",
  data: JSON.stringify({ name: 'N1', age : 1 }),
  contentType: "application/json; charset=utf-8",
  success: function (data) {
    console.log(data);
  }
});

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