Using the ASP.NET PageMethods

An easy way to start working with AJAX is using the PageMethods functionality. An example of using them is when a user is registering to your website and you want to check the availability of a user name against your data store and you want to spare yourself the hastle of creating a web service and calling it from the clientside code. I’ll explain how to create a PageMethod to satisfy this scenario.

What you need to do in the code behind file

1. Create a static method that checks the name
public static string CheckUserNameAvailable(string value)
if (value.Length < 8 )
throw new Exception( "User name length must be 8 or more");
if (value.ToLower() == "islam.shaalan")
return "0";
return "1";
throw new Exception("Please Specifiy a valid value");

2. Add an attribute [WebMethod] to the CheckUserNameAvailable static method.

In the HTML you’ll add a ScriptManager Tag to enable the usage of AJAX.

3. Add a script manager tag and set the EnablePageMethods to true.
<asp:ScriptManager ID="ScriptManager" runat="server"
EnablePageMethods="true" />

4. Create your interface
<input type="text" value="" id="userName"/>
<input type="button" value="Check Availability" onclick="CheckAvail();" />

Finally With The JavaScript

5. Create the CheckAvail() method that will call the CheckUserNameAvailable PageMethod and pass the value in the User Name text box.The method call can take 2 other optional parameters the onSuccess and onFailure. The onSuccess is called whenever the called method returns normally. If an uncaught exception is raised on the server the onFailure method is going to be called.
function CheckAvail() {
var userName = document.getElementById('userName');
PageMethods.CheckUserNameAvailable(userName.value, OnSucceed, OnFailure);
function OnSucceed(value) {
if (value == "0")
alert("UserName is already in use.");
alert("UserName is available.");
function OnFailure(error) {


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: