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="http://www.kindblad.com/wp-content/uploads/2008/04/progressbar.gif" /></div>

2. Add this to your stylesheet file:

#ProgressBar
{
 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 (progressBar.style.display == 'none' || progressBar.style.display == '')
 {
  // Show.
  // Center the progressbar.
  var bounds = getWindowBounds();
  progressBar.style.top = (bounds.y / 2) - 50 + 'px';
  progressBar.style.left = (bounds.x / 2) - 150 + 'px';
  progressBar.style.display = 'block';
 }
 else 
 {
  // Hide.
  progressBar.style.display = '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.
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(toggleProgressBar);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(toggleProgressBar);
</script>

That's it.