PageLoad event firing twice

On one of my projects I had the need to intercept the begin request and pageloaded event of page request manager. Begin request is an event raised by page request manager when a control inside of an UpdatePanel postback to the server. The event is raised just before the request is sent to the server. PageLoad event is a similar event but it gets raised the after the request has been received from the server and appropriate Update Panels have been updated. When I registered for pageloaded event and was manipulating the controls based on the data data received from the server, I was getting weird behaviors after resetting variables I had declared globally. To investigate the matter I put debug statements and sure enough confirmed that PageLoad event was firing twice. Here is an example that displays that behavior.

image

image

In the above code we are registering for PageLoad event for page request manager inside of PageLoad event. PageLoad is a global event that gets raised by the application object. It is a confirmed point at which we are sure that all the asp.net Ajax library has been loaded. In the registered PageLoad event, I am writing a trace statement to the console. Looking at the output for the firebug, you would notice that first time when the button is clicked, the trace gets written once and on a second time click the trace is written twice. The reason is the event handler has been registered twice. Therefore on the second postback we are adding another event handler causing the trace to be written twice or more depending on the number of times you clicked the button. What needs to be done here is register for an event handler only the first time the page is rendered on the client. It is a pretty simple fix. We can check the page request manager to see if its not an asynchronous request and than register our delegates. Here is the changed code.

image

image

3 Comments

  • Might be better to add a js script file like so:

    ///

    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

    function BeginRequestHandler(sender, args)
    {
    //async postback begin
    }

    function EndRequestHandler(sender, args)
    {
    //async postback end

    }

    and add a reference in your script manager:







    This way your custom script will execute only after the ajax library loads and you can avoid the async postback check.

    Raj

  • Good find i will keep that in mind.
    Thanks a lot!

  • Interesting finding, I always wonder why page_load is firing twice in some of my applications.

    Thanks for sharing

Comments have been disabled for this content.