c# - 从 javascript 调用 aspx.cs 方法

标签 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>
...

*注意我没有把...这实际上是上面一行后面所说的内容

最佳答案

$.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/

相关文章:

javascript - JqG​​rid 内联添加记录保存

c# - 在 C# 中实现全局常量的最佳方法是什么?

javascript - jQuery 向上/向下滑动效果不适用于 div

c# - 无法在屏幕保护程序的 DLL 'opengl32.dll' 中找到入口点

c# - Unity Build错误::audioinaec中的属性application @ allowBackups = false:与另一个值冲突

javascript - 我想通过javascript隐藏基于PHP条件的提交按钮

javascript - 需要在 redux 的 reducer 中向数组追加数据

c# - HttpRuntime.Cache 和 Session 有什么区别?

c# - 从 DataTable 中的行创建一系列匿名类型

c# - 如何使用 InternetSetOption?