Wednesday, October 19, 2011

Registering Client Side Script from Server-Side.. in a Web User Control.. in an UpdatePanel

If you've ever had to register client side script from the server-side, you know that in .NET 4.0, the way to do it on a normal ASPX page is to use the ClientScript.RegisterStartupScript syntax like below:

Normal ASPX Page
string Message = "Hello World!"; ClientScript.RegisterStartupScript(this.GetType(), "alert", string.Format("alert('{0}');", Message), true);

and if you need to register from within an update panel, you'll need to use a ScriptManager like the code below:

Within Update Panel
string Message = "Hello World!"; ScriptManager.RegisterStartupScript(this.GetType(), "alert", string.Format("alert('{0}');", Message), true);

However, I ran into a problem today where my above code didn't work because my UpdatePanel was within a Web User Control! What I figured out is that for the type parameter, you need the current PAGE type, not the user control type, so your code should look like this:

Within Update Panel Within A Web User Control
string Message = "Hello World!"; ScriptManager.RegisterStartupScript(this.Page.GetType(), "alert", string.Format("alert('{0}');", Message), true);

Ah the joys of updatePanels and Web User Controls. I hope this helps someone!

No comments:

Post a Comment