Saturday, April 26, 2008

Create a global progress bar for your ASP.NET AJAX applications

In ASP.NET AJAX you can use the UpdateProgress control to display a progress bar for asynchronous page updates. This control needs to be attached to a single UpdatePanel. If you need a consistent progress bar throughout your application, you will thus need to add one UpdateProgress control for every UpdatePanel control. Since this is not an ideal solution, then instead of using the UpdateProgress control, we can create our own progress bar by attaching a method to the beginRequest and endRequest event of the PageRequestManager class, which toggles the visibility of a div-container with an animated image. Have a look at the example below.

1. Start by adding a div-container with the following image to your master-page or web form:

<div><img alt="Progress bar" src="" /></div>

2. Add this to your stylesheet file:

 background: #FFFFFF;
 width: 300px;
 height: 100px;
 border: 1px solid #928F8F;
 position: absolute;
 display: none;
 z-index: 99999998;
#ProgressBar img
 position: relative;
 left: 43px;
 top: 38px;

3. Now we need a method to show and hide the progress bar. Add the following javascript code, make sure you add it below the ScriptManager control:

<script type="text/javascript">
// Toggles the visiblity of the progress bar.
function toggleProgressBar()
 var progressBar = $get('ProgressBar');

 if ( == 'none' || == '')
  // Show.
  // Center the progressbar.
  var bounds = getWindowBounds(); = (bounds.y / 2) - 50 + 'px'; = (bounds.x / 2) - 150 + 'px'; = 'block';
  // Hide. = 'none';
// Returns the height and width of the current window.
function getWindowBounds()
 var bounds = {x: 0, y: 0}
 if (self.innerHeight)
  // All except Internet Explorer.
  bounds.x = self.innerWidth;
  bounds.y = self.innerHeight;
 else if (document.documentElement && document.documentElement.clientHeight)
  // Internet Explorer strict mode.
  bounds.x = document.documentElement.clientWidth;
  bounds.y = document.documentElement.clientHeight;
 else if (document.body)
  // Internet Explorer.
  bounds.x = document.body.clientWidth;
  bounds.y = document.body.clientHeight;
 return bounds;

// Attach the ToggleProgressBar method.

That's it.