从javascript调用aspx.cs方法

时间:2012-03-29 04:24:45

标签: c# javascript asp.net json visual-studio-2010

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

* 注意我没有把...这就是上面一行之后所说的那些

3 个答案:

答案 0 :(得分:0)

  1. ScriptManager应该在您的页面上。
  2. ScriptManager.EnablePageMethods应设置为true。
  3. 也可以尝试更改此行:

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

答案 1 :(得分:0)

$.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的数据,并对你的变量进行字符串化。希望这会有所帮助..

答案 2 :(得分:0)

请确保您在clientRequest

中有此功能
data: "{'passedVal':'" + your_data+ "'}",

希望这对你有帮助!