繁体   English   中英

从javascript调用aspx.cs方法

[英]calling aspx.cs method from javascript

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

* 请注意,我没有在上面的行之后放...这就是它的全部内容

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

也可以尝试像这样更改此行:

 contentType: "application/json; charset=utf-8"
$.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的数据,并对变量进行字符串化。 希望这可以帮助..

只要确保您的clientRequest中有这个

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

希望这对您有所帮助!

暂无
暂无

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

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