我目前正在尝试调用 javascript 内的 aspx.cs 中的方法。
以下是我目前拥有的:
Javascript:
function loadPins(passValue) {
callServer2("myMethod", passValue);
}
function callServer2(requestMethod, clientRequest) {
var pageMethod = "Default.aspx/" + requestMethod;
$.ajax({
type: 'POST',
data: clientRequest,
dataType: 'JSON',
contentType: 'application/json',
url: pageMethod , //Method to call
success: function (result, status) {
alert("success");
},
error: function (xhr, status, error) {
alert("ERROR");
}
});
}
我的aspx.cs
:
[WebMethod]
public static string myMethod(string passedVal)
{
value = passedVal;
return "true";
}
当我调试时,我看到它调用并输入 CallServer2
但它似乎从未达到我的 aspx 中的断点。我也没有看到成功或错误消息警报。
有什么建议吗?
我当前遇到的错误:
error - <html>
<head>
<title> Unknow we method myMethod.<br>Parameter name:
methodName</title>
<style>
body{font-family:verdana";font-weight:normal;font-size:
.7em;color:black}
p
{font-family:"Verdana";font-weightbold;color:black;margin-top: -5px}
b{font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1{
font-family:"veranda";font-weight:normal;font-size:18pt;colour:red}
H2{
font-family:"Verdana";font-weight:normal ;font-size:14pt color:maroon}
pre{font-family:"Lucida Console";font-size .9em}
.marker{font-weight:bold;color:black;text-decoration:none;}
.version{color:gray;}
.error{margin-bottom:10px}
.expandable{text-decoration:underline, font-weight:bold; color:navy; cursor:hand;}
</style>
<head>
<code>
An unhanded exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
...
*注意我没有把...这实际上是上面一行后面所说的内容
最佳答案
$.ajax({ type: "POST",
url: pageMethod, contentType: "application/json; charset=utf-8",
data: "{passedVal:" + JSON.stringify(clientRequest) + "}", dataType: "json",
success: function (result, status) {
alert("success");
},
error: function (xhr, status, error) {
alert("ERROR");
}
});
您应该在数据中使用passedVal传递数据,并对您的变量进行字符串化。希望这有帮助..
关于c# - 从 javascript 调用 aspx.cs 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9919052/