Calling Server Side Methods From Client Side Code Using PageMethods

<%@ Page Language="C#" %>

<script runat="server">
    
    [System.Web.Services.WebMethod]
    public static bool IsTicketAvailable(int NoOfTickets)
    {
        int AvailableTickets = 5;
        return (NoOfTickets > AvailableTickets);
    }


</script>

<html>
<head>
</head>
<body>
    <form id="form1" runat="server">
    <script language="javascript">
        function callserver() {
            var tic = $get("txtNoOfTic").value;
            PageMethods.IsTicketAvailable(tic, OnSuccess, OnFailure);
        }

        function OnSuccess(result) {
            if (result) {
                alert("Please enter less number of ticket!");
                $get("txtNoOfTic").select();
            }
        }

        function OnFailure(error) {
        }

</script>
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        No Of Tickets:
        <asp:TextBox ID="txtNoOfTic" onchange="callserver()" runat="server"></asp:TextBox>
    </div> 
    
    </form>
</body>
</html>

Source

Some notes about this implementation:

  1. Must be static methods and as such you can’t call a non-static method inside the static method
  2. [WebMethod] only works on pages (aspx), not controls (ascx)
  3. Works in both single file (inline) and codebehind ASPX implementations
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s