从javascript调用aspx.cs方法

本文关键字:cs 方法 aspx 调用 javascript | 更新日期: 2023-09-27 18:29:16

我目前正试图在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>
...

*注意我没有把。。。这就是上方的行之后所说的全部

从javascript调用aspx.cs方法

$.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传递数据,并字符串化您的变量。希望这能有所帮助。。

  1. ScriptManager应该在您的页面上
  2. ScriptManager.EnablePageMethods应设置为true

也试着这样改变你的这条线:

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

只需确保您的客户端请求中有此信息

data: "{'passedVal':'" + your_data+ "'}",

希望这能帮助你!