简体   繁体   English

ASP.NET WebMethod使用参数获取Ajax

[英]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调用:

$.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: 您需要传递一个对象而不是字符串,并在n1周围加上引号以使其成为字符串:

$.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: 如果要使用url传递参数,则根本不需要使用data属性:只需将它们传递给url本身,如下所示:

 $.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);
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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