Home » CodeDigest


Calling a Serverside Method from JavaScript in ASP.Net AJAX - PageMethods
Submitted By Satheesh Babu B
On 2/3/2009 8:01:11 AM
Tags: 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,



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



         alert("Please enter less number of ticket!");




    function OnFailure(error) {





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


        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">


    No Of Tickets: <asp:TextBox ID="txtNoOfTic" onchange="callserver()" runat="server"></asp:TextBox>






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

Recent Codes
  • View All Codes..