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";
else
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
<label>UserName</label>
<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.");
else
alert("UserName is available.");
}
function OnFailure(error) {
alert(error.get_message());
}

Posting back an ASP.NET page from Javascript

A Postback is another name for HTTP POST. The contents of a form are sent to the server for processing some information. Afterward, the server sends a new page back to the browser.
In some scenarios you’d like to postback the page or part of the page if you’re using AJAX. All the ASP.NET server controls except the ImageButton and Button will call a JavaScript method called __doPostBack(eventTarget, eventArgument). This method is inserted to the page HTML output by the ASP.NET runtime engine. The method accepts 2 arguments

  • __EVENTTARGET: holds the ID of the control that’s raising the postback event
  • __EVENTARGUMENT: holds additional information that are required by the control on the server

//The __doPostBack method inserted by the ASP.Net runtime
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}

In order to do a postback from JavaScript code all you need is call the __doPostBack method, but this isn’t the best and safest way to perform the action. If the ASP.NET guys changed the name of the method your code will break. To prevent this you’ll need to use some server side code.
Create a method called DoPostBackJS().
function DoPostBackJS() {
<%= Page.ClientScript.GetPostBackEventReference(this, "posting back from js") %>
}

The line of code in the preceding method at runtime will be evaluated to
__doPostBack('__Page','posting back from js')