|
The page methods should be defined as a public static method and it should be decorated with WebMethod attribute. Refer the below page method that returns a string of available number of tickets at that moment.
|
|
| |
|
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetAvailableTickets()
{
int NoOfTicketsAvailable = 5;
return NoOfTicketsAvailable.ToString();
}
}
|
| Include System.Web.Services namespace for the above web method to work. |
| Calling the PageMethod using JQuery |
| We can use JQuery.ajax() method to call the PageMethod from client side, |
|
|
<script src="_scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function() {
$("#txtNoOfTickets").blur(function()
{
var ticketRequired = this.value;
var options = {
type: "POST",
url: "Default.aspx/GetAvailableTickets",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var avilabletic = parseInt(response.d);
if (ticketRequired > avilabletic) {
alert("Only " + response.d + " tickets available!");
}
else {
alert(response.d);
}
}
};
//Call the PageMethods
  $.ajax(options);
});
});
</script>
<form id="form1" runat="server"> <asp:TextBox ID="txtNoOfTickets" runat="server"></asp:TextBox>
</form> |
| You can download code for this tutorial. |