[英]How to call a server side method with a parameter (an object) using ajax where the url has query params?
I need to call the server side method MethodToBeCalledFromJS
from the client side. 我需要从客户端调用服务器端方法
MethodToBeCalledFromJS
。 The ajax call needs a url which contains query parameters. ajax调用需要一个包含查询参数的URL。 Where do I put the method name in the ajax call?
我在Ajax调用中将方法名称放在哪里?
This is the js code 这是js代码
$.ajax({
type: "POST",
url: "MyPage.aspx?queryParam1=value1&queryParam2=value2",
data: "{ Param1: " + JSON.stringify(myObject) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
alert(msg);
},
error: function (x, e) {
}
});
And I need to call the following function in C# 我需要在C#中调用以下函数
[WebMethod]
public string MethodToBeCalledFromJS(MyObject obj)
{
return "successful!";
}
在您的网址中添加MethodName
url: "MyPage.aspx/MethodToBeCalledFromJS?queryParam1=value1&queryParam2=value2",
Try this: 尝试这个:
$.ajax({
type: "POST",
url: "MyPage.aspx",
data: { 'obj': JSON.stringify(myObject),
'param2': 'myOtherValue'},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
alert(msg);
},
error: function (x, e) {
}
});
The method to call must be after aspx page name. 调用方法必须在aspx页面名称之后。 You can pass parameters directly in
data
: 您可以直接在
data
传递参数:
$.ajax({
type: "POST",
url: "MyPage.aspx?MethodToBeCalledFromJS",
data: "{ obj: " + JSON.stringify(myObject) + ", queryParam1: value1, queryParam2: value2 }",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
alert(msg);
},
error: function (x, e) {
}
});
And then your method: 然后你的方法:
[WebMethod]
public string MethodToBeCalledFromJS(MyObject obj, string queryParam1, string queryParam2)
{
return "successful!";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.