Friday, August 13, 2010

Page Methods

This article is all about the page methods and their usage. PageMethods is the part of Ajax.net and Script Manager.
MS Ajax gives us ability to directly create a web method on aspx page. And also enable to directly call this web method from the page. This method is termed as Page Method.
This is very easy way to implement Ajax functionality on the page. Like ICallback event handler here also we need to manipulate the string.
Page Method works simply as Web Methods
Script Manager Play critical role for the use of Page Methods, we need to set EnablePageMethods attribute to true.

To use web method attribute in Aspx page, use namespace
using System.Web.Services
Page Method should be static, as per the design by MS. So our web method (Page Method) will be as follows.

Now to call above method from client script we need to add PageMethods before the method name
PageMethods.HelloUser("Test User");
This will simply call the Method defied in Page, i.e. .cs file
Many times we need to handle different methods in different way, so in that case we need some special mechanism to handle the response from the server. We may also need to handle method failure errors in some customized way; we can also achieve this by adding extra parameters in PageMethods call.
In short we can add callback methods for successful invocation of pagemethods as well as for the failure of the pagemethod.

Basic Method prototype is
PageMethods.MethodName([para1,para2,…],[OnSucceeded, defaultFailedCallback,userContext]);

Above code work perfectly for normal scenario.
There might be possibility that we create our own JavaScript wrapper class, which internally uses PageMethods in that’s case, we might have following requirements.
  • Set defaultFailedCallback
  • Set defaultSucceededCallback
  • get defaultFailedCallback
  • get defaultSucceededCallback
  • set timeout
  • get timeout
Let’s say we have defined default Failed and Succeeded callbacks. Thus whenever we call some method like PageMethod.HelloUser(username), now if this method call completes its execution successfully our default Succeeded callback function will be called automatically. If method throws some error or failed, default Failed callback function will be called.
Also we need to call some already existing PageMethods but from some other pages; then in that case we should be able to set the path of the page in which methods are defined.
Considering above requirement we can modify the code as below.

With this understanding we can use pageMethods very effectively to handle static Page methods.

Download Demo Code here --> PageMethod3.5.zip

Submit this story to DotNetKicks

0 comments: