Calling PageMethods with
parameters
The code in previous section discussed
about calling a page method without passing parameters. In this section, we will
see how to call PageMethods with parameters.
We will have 2 PageMethods, one will
check for available number of tickets for males and the other will check for the
available number of tickets for females.
Codebehind
public partial class
CallServerWithParameters : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
}
[WebMethod]
public static string
GetAvailableTicketsForMales(int no)
{
string result = "";
int NoOfTicketsAvailable =
5;
if (no >
NoOfTicketsAvailable)
{
result = "Only " +
NoOfTicketsAvailable.ToString() + " Male ticket(s) avaialable. Please enter a
lower number!";
}
return result;
}
[WebMethod]
public static string
GetAvailableTicketsForFemales(int no)
{
string result = "";
int NoOfTicketsAvailable =
5;
if (no >
NoOfTicketsAvailable)
{
result = "Only " +
NoOfTicketsAvailable.ToString() + " Female ticket(s) avaialable. Please eneter a
lower number!";
}
return result;
}
}
ASPX
<script src="_scripts/jquery-1.2.6.js"
type="text/javascript"></script>
<script
language="javascript">
$(document).ready(function()
{
$("#txtNoOfMales").change(function() {
var ticketRequired =
this.value;
var options =
{
type:
"POST",
url:
"CallServerWithParameters.aspx/GetAvailableTicketsForMales",
data: "{no:" +
ticketRequired + "}",
contentType:
"application/json; charset=utf-8",
dataType:
"json",
success:
function(response) {
if
(response.d != "") {
alert(response.d);
$("#txtNoOfMales").focus();
}
}
};
//Call the
PageMethods
$.ajax(options);
});
$("#txtNoOfFemales").change(function() {
var ticketRequired =
this.value;
var options =
{
type:
"POST",
url:
"CallServerWithParameters.aspx/GetAvailableTicketsForFemales",
data: "{no:" +
ticketRequired + "}",
contentType:
"application/json; charset=utf-8",
dataType:
"json",
success:
function(response) {
if
(response.d != "") {
alert(response.d);
$("#txtNoOfFemales").focus();
}
}
};
//Call the
PageMethods
$.ajax(options);
});
});
</script>
<div>
No of Male Tickets:<asp:TextBox
ID="txtNoOfMales" runat="server"></asp:TextBox>
No of Female Tickets:<asp:TextBox
ID="txtNoOfFemales" runat="server" ></asp:TextBox>
</div>
The above code will alert the user with
a message if they enter number of ticket more than the tickets available in that
moment. For easy understanding, I have hard-coded the number of tickets
available in the PageMethods.
|