C#函数返回一个值,并显示在网页函数、网页

2023-09-10 17:37:46 作者:赴一场爱意

我做了下面的函数在C#中我apx.cs文件

I made following function in C# in my apx.cs file

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

和我想要显示的消息(世界你好)时,该功能在我的aspx文件调用我的脚本

And i'm trying to show the message ("hello world") when the function is called by my script in my aspx file

<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我的C#功能?

When I click on the button send I get an alert with the message 'undefined' so my var 'msg' is undefined but how can I put the 'hello world' from my C# function in the msg var?

感谢

推荐答案

这不是你收到消息。

像这样

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

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

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

您成功的功能将得到函数调用作为参数的结果。

Your success function will receive the result of the function call as a parameter.