CODEDIGEST InstallShield
Home Articles CodeDigest Tutorials InstallShield FAQs
Skip Navigation LinksHome » CodeDigest » Calling a Serverside Method from JavaScript in ASP.Net AJAX - PageMethods   You are not logged in.
Search
 

Sponsors
InstallShield
 

Sponsored Links
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Calling a Serverside Method from JavaScript in ASP.Net AJAX - PageMethods
Calling a Serverside Method from JavaScript in ASP.Net AJAX - PageMethods
Submitted By Satheesh Babu
On 2/3/2009 8:01:11 AM
Tags: asp.net ajax,CodeDigest,javascript  

Calling a Serverside Method from JavaScript in ASP.Net AJAX - PageMethods

ASP.Net AJAX introduced a technique called PageMethods using which we can call server side methods from JavaScript.

There are situations where we want to call a server side function from javascript to do some validations. For example, implementing a feature that checks for user name availability or a feature that checks for available number of tickets at that moment in a ticket booking system.

 

PageMethods in ASP.Net AJAX can be used in such scenarios. This little code snippet will explain how to implement a ticket availability check using PageMethods in ASP.Net AJAX.

 

How to implement?

PageMethods are implemented as a public static method and should be decorated by WebMethod attribute. To call this PageMethods from JavaScript, we need to set EnablePageMethods property to true. This will inject a JavaScript proxy class to call all the server side method that is decorated with WebMethod. Refer the below code snippet,

 

    [WebMethod]

    public static bool IsTicketAvailable(int NoOfTickets)

    {

        int AvailableTickets = 5;

        return (NoOfTickets > AvailableTickets);

    }

 

Include System.Web.Services namespace for the above code to work.

 

To call the above method from JavaScript,

<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>

<body>

    <form id="form1" runat="server">

 <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>

 

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!