0

I am not able to pass a value from Javascript to code behind. The result value is always undefined.

I have attached the code:

    <input id="Button2" type="button" value="FunctionCall" onclick="CallingServerSideFunction()" />
<script type="text/javascript">

    function CallingServerSideFunction() {
        alert("start");
        var result =PageMethods.Add(1,2);
        alert(result);
    }

</script>

</form>

My cs code: public static int Add(int x, int y)

    {
        int k = x + y;
        return k;
    }

Help me out with this!

Cris
  • 1
  • 1
    Check the accepted answer in this [SO](https://stackoverflow.com/questions/4313532/pagemethods-in-asp-net) post – Thangadurai Dec 19 '18 at 12:09

1 Answers1

0

It happen because the PageMethods calling asynchronously so the alert showing before the web method result assign in variable result.

I hope below code will help.

Javascript:

<script type="text/javascript">
    function CallingServerSideFunction() {
        PageMethods.Add(1, 2, OnSuccess);
    }
    function OnSuccess(response, userContext, methodName) {
        alert(response);
    }
</script>

HTML:

<input id="Button2" type="button" value="FunctionCall" onclick="CallingServerSideFunction()" />

C#:

[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static int Add(int x, int y)
{
    int k = x + y;
    return k;
}
Jitendra G2
  • 1,196
  • 7
  • 14