Friday, January 1, 2010

Calling a Serverside Method from JavaScript in ASP.Net AJAX

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,













No Of Tickets: