ASP.NET Ajax PageMethods
ASP.NET Ajax PageMethods
Introduction
During the making of a
ASP.NET Ajax lecture
which I’m scheduled to
do on this Monday,
I made some code
examples that include
a PageMethods example.
In this post I’ll explain what
are PageMethods and how to
use them in your ASP.NET application.
What are PageMethods?
ASP.NET Ajax extensions came with full support for script services. But sometimes
you don’t want to build a web service for a small piece of code or for basic functionality.
This is why the
PageMethods feature was created.
The
PageMethods feature enables the using of code-behind page methods on the client
side. The
PageMethods can only be added to the page itself so don’t try to add them to
user controls or custom controls - it won’t work.
How to Use PageMethods?
Basically, all you need to do in order to use a PageMethod is to decorate your page
method with the ScriptMethod and WebMethod attributes or only with WebMethod
attribute. Another restriction is that the method have to be static (or else it won’t work).
After the decoration of the method and also the existence of ScriptManager in your page
the method can be accessed from the client side using the PageMethods object.
PageMethods Example
Lets look at a simple example of how to use PageMethods.
In the page I have put the following method which returns a “Hello” string:
[ScriptMethod, WebMethod]
public static string GetLabelText()
{
return "Hello";
}
On the client side I have the following scripts which run that method:
<script type="text/javascript">
function InsertLabelData() {
PageMethods.GetLabelText(onSuccess, onFailure);
}
function onSuccess(result) {
var lbl = document.getElementById('lbl');
lbl.innerHTML = result;
}
function onFailure(error) {
alert(error);
}
InsertLabelData();
</script>
Also, in the page I hold a single Html label with a lbl id.
When the page is loading the “Hello” string will be attached to the label.
Pay attention to the PageMethods.GetLabelText call which calls the server side
method from the client side.
Summary
Lets sum up the post, I explained what are PageMethods.
I also showed a simple example of how to use a PageMethod.
The PageMethods feature is a very nice feature that you can use in the arsenal
of Ajax tools.