Executing ClientScript Before and After an Asynchronous PostBack using ASP.NET AJAX

A user recently mailed me to find out if there is a way to determine, when an asynchronous postback begins and ends in an ASP.NET AJAX page. He wanted to fire some JavaScript code during these events. Here’s how to determine the events.
During the AJAX client-side execution cycle of a page containing the ScriptManager control, the Application.init event is raised when the page is requested for the first time. We can use this event to wire up the client events that occur during an async postback. For this purpose, we use the Sys.WebForms.PageRequestManager class that raises client events specific to asynchronous postbacks.
Now the beginRequest and endRequest events of the Sys.WebForms.PageRequestManager class are raised before an async request and after an async response respectively. We will use these events to execute our JavaScript code as demonstrated below.
Note: I am using Visual Studio 2008 and thereby utilizing the ASP.NET AJAX plumbing that comes along with it.
Open VS 2008. Click File > New > Website. Choose ASP.NET Website from the list of installed templates, choose target platform as .NET Framework 3.5, choose the desired language and enter the location where you would like to store the website on your FileSystem. I have created a folder called VS2008 Projects, so the location over here is C:\VS2008 Projects\ ExecuteClientScriptDuringAsyncPostback. After typing the location, click OK.
Open Default.aspx. Switch to the Design mode of Default.aspx. Open the toolbox (Ctrl+Alt+X). Now add a <ScriptManager> control to the page and then an <UpdatePanel>. Inside the <UpdatePanel>, add a label and a button control as shown below

Just below the </body> tag, add the following script

As described above, we use the Application.add_init() to add the beginRequest and endRequest event handlers. To add or remove handlers for events raised by the PageRequestManager classes, use the add_eventname and remove_eventname methods of those classes.
Inside these handlers, we call our JavaScript functions beforeAsyncPostBack and afterAsyncPostBack respectively.
That’s it. Run the page. When you click on the button, just before an Asynchronous request, the beforeAsyncPostBack() gets executed.
Before Async
Similarly, after an Asynchronous response, the afterAsycPostBack() gets executed.
I hope you liked the article and I thank you for viewing it.


Popular Posts