Wednesday, 4 February 2009

Handling exceptions in UpdatePanel & UpdatePanelAnimationExtender

UpdatePanelAnimationExtender allows you to add eye-catching animations to your UpdatePanel indicating that update is in progress. However, it doesn't directly support error handling.

The following code defines UpdatePanelAnimationExtender for UpdatePanel MyUP. The panel will fade out each time the update starts and fade in after successful update.
<cc1:UpdatePanelAnimationExtender
ID="MyUPAE"
BehaviorID="UpdateAnimation"
runat="server"
Enabled="True"
TargetControlID="MyUP">
<Animations >
<OnUpdating >
<Parallel duration="0">
<FadeOut minimumOpacity=".5" />
</Parallel>
</OnUpdating>
<OnUpdated>
<Parallel duration="0">
<FadeIn minimumOpacity=".5" />
</Parallel>
</OnUpdated>
</Animations>
</cc1:UpdatePanelAnimationExtender>
If the code executed during update causes an error the browser may warn you about JS error (caused by actual server side error) but the panel will remain faded out. Browser's warning is usually hard to notice or even not displayed at all.

Solution:
The following JS code allows you handling update errors on client side. It assumes that there is a span element defined on that page for displaying error messages (with ID=ErrorMsg).
<script type="text/javascript">

// Create EndRequest handler for update panel
Sys.WebForms.PageRequestManager.getInstance().
add_endRequest(EndRequestHandler);

function EndRequestHandler(sender, args)
{
// If there is an unhandled error
if (args.get_error() != undefined)
{
// create error message and display it
var errorLbl = $get('<%=ErrorMsg.ClientID%>');
errorLbl.innerHTML = 'An error occurred while completing update.';

// end update panel animation
var upAnimation = $find('UpdateAnimation');
upAnimation._postBackPending = false;
upAnimation.get_OnUpdatingBehavior().quit();
upAnimation.get_OnUpdatedBehavior().play();

args.set_errorHandled(true);
}
}
</script>

3 comments:

Anonymous said...

Hi Filip- A quick question about the line below:

var upAnimation = $find('UpdateAnimation');

You are using $find to search for the BehaviorID of the UpdatePanelExtender and not the ID... like $get('MyUPAE') does this work? If I try this on a .NET masterpage would I have to $find the behaviorID like $find('$Ctrl001_UpdateAnimation') ??

Thanks for posting... --TK

Filip Czaja said...

To access the UpdatePanelAnimationExtender from "outside" the control I would try smth like:
$find('<%=ControlID.UpdateAnimation.BehaviorID%>')

Mahesh Sharma said...

How do I add those little graphics to this extender?
Like those little animations like circles or progress bars which we see everywhere when any updates are done.