【问题标题】:C# functions returns a value and show in webpageC# 函数返回一个值并显示在网页中
【发布时间】:2013-03-13 11:46:39
【问题描述】:

我在我的 apx.cs 文件中用 C# 编写了以下函数

[WebMethod]
public static string  SendForm()
{
    string message = "hello world";
    return message;
}

当我的脚本在我的 aspx 文件中调用该函数时,我试图显示消息(“hello world”)

<script>
    function SendForm() {
        var msg;
        msg = PageMethods.SendForm(OnSucceeded, OnFailed);

        function OnSucceeded() {
            alert(msg);
        }

        function OnFailed(error) {
            // Alert user to the error.
            alert("failed");
        }
    }
</script>
    <body>
    <form id="Form1" runat="server">
   <asp:ScriptManager ID="ScriptManager" runat="server"
       EnablePageMethods="true" />
   <fieldset id="ContactFieldset">
        <input type="button" onclick="return SendForm()" value="send" />
   </fieldset>
</form>
</body>

当我点击按钮发送时,我收到一条带有“未定义”消息的警报,因此我的 var 'msg' 未定义,但是如何将 C# 函数中的“hello world”放入 msg var 中?

谢谢

【问题讨论】:

  • 您能告诉我们您使用的是什么 .Net 框架吗?

标签: javascript asp.net ajax asp.net-ajax


【解决方案1】:

这不是您接收消息的方式。

这样做

   function SendForm() {
        PageMethods.SendForm(OnSucceeded, OnFailed);

        function OnSucceeded(msg) {
            alert(msg);
        }

        function OnFailed(error) {
            // Alert user to the error.
            alert("failed");
        }
    }

您的成功函数将接收函数调用的结果作为参数。

【讨论】:

    【解决方案2】:

    尝试使用

     function OnSucceeded() {
            alert(msg.d);
        }
    

    编辑-1

    请通过此链接
    How do I call a particular class method using ScriptManager

    【讨论】:

    • 如果 msg 未定义,它如何从中获取值?
    • @Eclectica_ 我提供了一个链接。
    【解决方案3】:

    我不确定您使用的是哪个版本的 .Net 框架,但如果是 3.5,那么您可能需要查看以下链接:

    http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/

    从 asp.net 3.5 开始,响应被包裹在 .d 中。

    【讨论】:

      【解决方案4】:
          function SendForm() {
              var msg;
              msg = PageMethods.SendForm(function (result) {
                  alert(result);
              }, function (error) {
                  alert(error);
              });
          }
      

      这应该可以。

      如果从 SendForm 方法抛出异常,它会自动转到错误方法。

      [WebMethod]
      public static string  SendForm()
      {
          throw new Exception("Error");
      
          string message = "hello world";
          return message;
      }
      

      【讨论】:

        猜你喜欢
        • 2022-10-14
        • 2021-05-30
        • 1970-01-01
        • 2017-07-11
        • 2014-01-02
        • 2020-02-29
        • 1970-01-01
        • 1970-01-01
        • 2013-09-24
        相关资源
        最近更新 更多