Monday, October 5, 2009

Asp.Net Ajax PageMethods

How Do I? use PageMethods in Asp.Net


PageMethods are asp.net way of light weight Ajax communication. Update panels are known for rapid development and ease of use but they have worst performance and speed issues. AJAX is associated with performance and update panel is performance killer. It lacks speed and heavy on the wire.

Let’s face it; Update panel is designed to follow the normal asp.net page life cycle. This makes sure ease of use but not performance and speed.

But there is a way of performance and speed in asp.net Ajax we just need to learn living without update panels and start doing some manual work.

PageMethods are designed in such a way, we can easily start using them by following simple steps but there are also some things developers should know before using them.

PageMethods are static

that implies

1- They don’t follow asp.net life cycle

2- They can’t use global variables other than static variables

ALERT

Don’t use static variable, they are shared among all users and have the scope of application variables.

Why PageMethods are static?

1- Static methods can be called without initializing the class they are in that’s why they don’t require to follow the asp.net page life cycle

2- To overcome the update panel and callback way of communication; both these methods sends all the viewstate in request and follows the normal page life cycle that starts from page load method not from the calling functions.

How to implement PageMethods

Now you just require following step by step guide to start using page methods. In this tutorial, I will show you how you can wrote a simple PageMethod, use it efficiently in your code and in next tutorial, I will show you how you can send more complex data in page methods.

So let’s begin this journey;

Step 1:

Create a new project in either visual web developer or visual studio

Step 2:

Add the assembly to use with page method


Step 3:

Write the method. This method as shown in the below image will take the first name as the argument and will greet the user if name present of throw and exception if null or empty.

Step 4:

Add script manager with EnablePageMethods=”true”


Step 5:

Add html text box and button to take user input of first name and then call server with this value


Step 6:

Write java script to call the page methods.


As you can see in this picture, I have a method callPageMethods and this method takes the value from text box and call server with this. Calling PageMethods requires 3 parameters

1- Argument that will be passed to PageMethods on the server

2- A function name that will receive the result when this call will executed successfully

3- A function name that will receive the error in case of unexpected happen or you program your exceptions to throw, in this example I have thrown the exception if I used didn’t input his/her name in text box.

Results:


As you can see, first time I did enter my first name and it throws the exception and javascript function onFail cached this error and alert the error.

In this picture you can see the successfully hello world method is executed and I have received the message in alert box.

I have these screen shots of firebug to show you how much data is transferred.

1- Post


Only few Bytes

This picture also highlited the error as shown in firebug. This is not an error. This was the exception thrown by the server when i didnt enter the first name and hit the submit button. This is a handled exception and handled exceptions are GOOD ONES.

2- Response


Only few Bytes as well

That’s the benefit of PageMethods we are not sending receiving too much data as in case of update panel or call back when whole viewstate along with other fields post to server and user has to wait for longer time as request will go through whole asp.net page life cycle and then results will be sent back to client.

In next tutorial, I will show you how you can send more complex data using PageMethods and I will discuss the JSON as the whole communication of PageMethods is done through JSON format.

7 comments:

  1. Hi
    I am using PageMethods heavily in my application now we have some requirement where some process is running its background process which is update the Database and set some flags, so now whenever I will perform any operation it will redirect me to some other page due to the background process, I can redirect my page in any postback but in PageMethods I am not able to get this event I have used application_AcquireRequestState in Global.asax where in PageMethods request it also fire this event but not able to redirect to another page can u suggest me how can i get the event in page or in common location when any PageMethods get fired.

    ReplyDelete
  2. Hi vikrant,
    you can always use predefined exceptions. e.g. in your scenario, i will create an exception

    public class RedirectException : Exception
    {

    public RedirectException() : base()
    {
    }

    public TextException(string message) : base(message)
    {

    }
    }

    now throw this exception and handle it in your asp.net aspx page method error function

    here is how you do it...

    first you throw it from your page method
    [WebMethod]
    public static bool GetData(string param1)
    {
    if(condition)
    throw new RedirectException("my\redirect\url.aspx");
    }

    and then handle it in your erro method of relevent page mehtod. By default the Exception is passed in XMLHttpRequest object and you can get the Exception Type and Message by parsing it to JOSN. Below function will show you how you could do it


    function GetData_Error(XMLHttpRequest, textStatus, errorThrown)
    {

    var errorMsg = eval("(" + XMLHttpRequest.responseText + ")");
    if(errorMsg.ExceptionType=="RedirectException")
    {
    //to redirect
    window.location=errorMsg.Message;;
    }
    else alert(errorMsg.Message);
    }

    I think this will solve your problem. If you still have problem please let me know.

    ReplyDelete
  3. Hi dude, you rocks. You explanation is clear and very informative. waiting for your next tutorial of page methods using json.

    ReplyDelete
  4. Adeel bhai, fit ho? yar woh credit hi nahi hay mobile may or jaib may paisay bhi nahi hay. pay 15 ko milni hay mtbc say check. is lia sms ka reply nahi kar saka. bas dakho kab agla article likhta ho...

    ReplyDelete
  5. This is a very nice article. Thank you for doing such a nice job of explaining it in such an easy to understand manner. However, I want to mention something that was giving me fits.

    No matter what I did, the error thrown by my C# code-behind WebMethod would not propagate down to the JavaScript running on the client. I kept getting "Unhandled exception" errors in the Server side code. I finally figured out that in order for this to work in Debug mode in Visual Studio 2013, you need to go to DEBUG/Options and Settings/Debugging/General and turn off the "Enable Just My Code" option. Once I did this, then it worked and the error was propagated back to the client JavaScript error handling function.

    Thanks again for a wonderful article.
    Dave

    ReplyDelete
    Replies
    1. Hi Dave, this is a very old article. Please do not use page methods. Use web Services,Rest Services,mcv controllers or web api. do not invest your time into this obsolete technology.

      Delete