Monday, June 9, 2014

Get the return value from ASP.NET Code behind function to the client using JQuery

Using Ajax POST method you can call ASP.NET Server side C# function from the client side. Here the GetSquareOfNumber function is called from client side and return the calculated value from the server when we click the Button2. The c# function should be static, decorated using [WebMethod] attribute and the parameter variable should be same as one we used in the ajax call "param". The returned value will be retrieved in the ajax success function. Use the Breakpoint to check the server code getting called or not.
Script in ASPX page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function ()
        {
            $("#Button2").click(function ()
            {
                var num = $('#TextBox1').val();
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/GetSquareOfNumber", // Your page and function name
                    data: '{param: "' + num + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data)
                    {
                        if (data.d != null)
                        {
                            alert(data.d);
                        }
                    },
                    failure: function (response)
                    {
                        console.log(response.d);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <input id="Button2" type="button" value="button" />
        </div>
    </form>
</body>
</html>

Namespace:

using System.Web.Services;

Code behind C#:

[WebMethod]
public static int GetSquareOfNumber(int param)
{
 return param * param;
}

No comments:

Post a Comment