C# functions returns a value and show in webpage

2019-05-16 11:19发布

问题:

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

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

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>

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?

thanks

回答1:

Thats not how you receive the message.

Do it like this

   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.



回答2:

Try using

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

Edit -1

Kindly go through this link
How do I call a particular class method using ScriptManager



回答3:

I'm not sure what version of .Net framework are you using, but if it is 3.5 then you may want to check following link:

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

In asp.net 3.5 onward, response is wrapped in .d.



回答4:

    function SendForm() {
        var msg;
        msg = PageMethods.SendForm(function (result) {
            alert(result);
        }, function (error) {
            alert(error);
        });
    }

This should work.

If you throw an exception from the SendForm method, it automatically goes to error method.

[WebMethod]
public static string  SendForm()
{
    throw new Exception("Error");

    string message = "hello world";
    return message;
}