PageMethods can be implemented by the following steps.
1. Include the Services namespace.
using System.Web.Services;
2. Add a public static method to your code behind page and decorate with [WebMethod].
[WebMethod]
public static string GetSalutation()
{
var salutation = string.Empty;
var hour = DateTime.Now.TimeOfDay.Hours;
if (hour >= 0 && hour <= 11)
{
salutation = "Good Morning!";
}
else if (hour >= 12 && hour <= 16)
{
salutation = "Good Afternoon!";
}
else
{
salutation = "Good Evening!";
}
return salutation;
}
3. Add ScriptManager control from the Ajax Extensions tab on the Visual Studio toolbox.
4. Enable page methods in your app by adding EnablePageMethods=”true” to the Scriptmanager markup.
5. Write javascript to call the pagemethod and handle the result.
function GetGreeting()
{
PageMethods.GetSalutation(onSucess, onError);
function onSucess(result)
{
var ctrl = document.getElementById("Greeting");
ctrl.value = result;
}
function onError(result)
{
alert('Cannot process your request at the moment, please try later.');
}
}
6. Create an interface with elements for invoking the javascript method and displaying the results;
<input onclick="GetGreeting()" type="button" value="Go" /> <input id="Greeting" type="text" value="" />
Possible Issues
1. The scriptmanager must be placed inside the pages Form tags, it it is not an exception will be thrown;
‘ScriptManager’ must be placed inside a form tag with runat=server
2. If you miss off enabling the pagemethods on the scriptmanager a javascript error will be thrown;
‘PageMethods’ is undefined
Final Note
Interacting with page controls must be done in the javascript side as page controls cannot be accessed from with a pagemethod. So any values you need from page controls will need to be passed to the page methods as parameters.
I have added a visual studio project containing a couple of examples including the one above to Github.
