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