Friday, February 13, 2009

Disable user interface during ajax postbacks on ASP.Net

One of the biggest issues I have with public facing websites I work on is double clicks on buttons or users interrupting the postback process. This happens a lot with the payment button of credit card transactions and other time consuming postbacks.
I have done some Javascript and CSS tweaks and tricks to handle specific controls and I was unable to get something I was truely happy with.
Until I met jQuery. jQuery is a javascript library that does a whole bunch of things, introduces shortend syntax and a pluggable API. It can be downloaded at http://jquery.com/.
Coupling JQuery with a plugin called BlockUI. Can be downloaded at http://malsup.com/jquery/block/
What I came out with is a fairly generic solution for ASP.Net that handles all the ajax postbacks for a specific page or website by wiring the application_beginRequest and application_endRequest on the client side.
So here is the recipe:
Ingrediants -
1. ASP.Net 3.5 website
2. An aspx webpage
3. A script manager with a reference to:






  1. The JQeury library



  2. Block UI plugin



  3. A very short Javascipt file (enclosed below)



4. An update panel




Instructions:




1. Create your website - I use Visual Studio 2008




2. Add your page or your master page




3. Create a js directory and add the downloaded scripts from jQuery and JBlockUI




4. Add a new file to the js directory called wireRequestEvents.js




with the following code:





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





Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args)
{
$.blockUI();
}
function EndRequestHandler(sender, args)
{
$.unblockUI();
}




5. Drop a script manager in your page with the following syntax:














6. Add your update panels with contect templates and you are good to go.


To demonstrate the technique I created a simple page with a button and a label inside an update panel. Once clicked the button waits 4 seconds and then changes the label. This imulates a long transaction on the server.




Here is what the users will see:





After they click the button the UI is blocked by a semi transperant div





When the request returns the users will see the updated screen




Pretty simple!

The code for this is available at http://www.simplicityc.com/files/JQuerySample.zip