Archive for July, 2007

Injecting JavaScript from an Ajax Update Panel

I started using the Update Panel control recently to verify that an email address entered on a registration form was not a duplicate.  If the email address as a duplicate, I wanted to display a simply JavaScript alert to notify the user without resorting to hidden fields.  After much searching  I found the The PageRequestManager Class and was able to leverage endRequest Event.

By adding the following PageRequestManager calls to a JavaScript block you can tap into the Begin and End AsyncPostback events 

<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BegRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);

function BegRequest(sender, args)
{
    // add client-side code here
}

function EndRequest(sender, args)
{
     // add client-side code here
}
</script>

Also, using the RegisterStartupScript method of the ScriptManager class you can easily inject JavaScript onto a page in a manner that’s almost identical to Page.ClientScript.RegisterStartupScript() method.  Here’s an example of the ScriptManager call to inject a JavaScript alert.

ScriptManager.RegisterStartupScript( upDependents, typeof( UpdatePanel )
   ,Guid.NewGuid().ToString(), string.Format( "DisplayErrorMessage('{0}');"
   ,errorMessage ), true );