In addition to allowing XML-HTTP requests to call conventional Web service methods, ASP.NET AJAX also supports a special type of Web method known as the page method. Page methods are Web service methods implemented in Web pages (*aspx). This means there is no need for a conventional ASMX (Web services) file. Page methods enable developers to trigger XML-HTTP type call-backs (in other words, there is no need for a PostBack to the server) without building dedicated Web services.
Page methods must be public static methods and must be decorated with the [WebMethod] or [ScriptMethod] attribute. Your page must be ajax enabled, meaning a ScriptManager must be present (Set the EnablePageMethods attribute to true)
[WebMethod]
public static string example(int var1, int var2)
{
return "This string was returned by the Page Method with values" + var1 + " and " + var2;
}
PageMethods can return any variable type and even objects as long as it is serializable.
The setup for using PageMethods is now complete. Let’s have a look at how to put it all together.
Using JavaScript, call the webmethod as defined in your aspx.cs file by making use of the PageMethod object.
function btnSomething_Click()
{
var var1 = 10;
var var2 = 20;
PageMethods.example(var1, var2,
function success(result, context, methodName)
{
window.alert(result + ‘ was returned by ‘ + methodName);
},
function failed (err, context, methodName)
{
window.alert(methodName + "\n" + err.get_message());
},
“this is a context variable” );
}
Successful execution resulted in the success javascript function being called. This method receives three parameters. Result contains the value returned by the PageMethod.
If the PageMethod could not be called, or something went wrong in returning a value back to the client the failed javascript method is called.
In the above example, both the successful () and failed () functions received a parameter called context. This is a optional parameter that can be supplied by the user in the original PageMethod call. The value of the user context variable will now contain the value “this is a context variable”. If nothing was passed to the page method, this value will be null. We use PageMethods religiously when the client expects increased performance and response times. Combined with a healthy understanding of HTML rendering and Stylesheets (see our blog on CSS) there is little a well-constructed Javascript function using Pagemethods cannot do.
And that is all that is to it. Easy!
Carel Steenkamp
No comments:
Post a Comment