Monday, June 9, 2014

Call and pass parameter to ASP.NET Code behind function from the client side using JQuery

Using Ajax POST method you can call ASP.NET Server side C# function from the client side with parameter also. Here the SendTheID function is called from client side and the TextBox1 value will be passed as a parameter 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". 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/SendTheID", // Your page and function name
                    data: '{param: "' + num + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data)
                    {
                        //will return null
                    },
                    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 void SendTheID(int param)
{
 int returnId = param;
//Write whatever you neeed..
}

No comments:

Post a Comment