Monday, June 9, 2014

Call ASP.NET Code behind function without parameter from the client side using JQuery

Using Ajax POST method you can call ASP.NET Server side C# function from the client side. Here the RunMe function is called from client side when we click the Button1. The c# function should be static and decorated using [WebMethod] attribute. 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 ()
        {
            $("#Button1").click(function ()
            {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/RunMe", // Your page and function name
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (res)
                    {
   //will return null
                        console.log(res);
                    },
                    failure: function (response)
                    {
                        console.log(response.d);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <input id="Button1" type="button" value="button" />
        </div>
    </form>
</body>
</html>

Namespace:

using System.Web.Services;

Code behind C#:

[WebMethod]
public static void RunMe()
{
//Write whatever you neeed..
}