Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work asp.net asp.net

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work


I had an issue using this in a user control (in a page this worked fine); the Button1 is inside an updatepanel, and the scriptmanager is on the usercontrol.

protected void Button1_Click(object sender, EventArgs e)  {      string scriptstring = "alert('Welcome');";      ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscript", scriptstring, true);  }

Now it seems you have to be careful with the first two arguments, they need to reference your page, not your control

ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "alertscript", scriptstring, true);


I think you should indeed be using the Control overload of the RegisterStartupScript.

I've tried the following code in a server control:

[ToolboxData("<{0}:AlertControl runat=server></{0}:AlertControl>")]public class AlertControl : Control{    protected override void OnInit(EventArgs e){        base.OnInit(e);        string script = "alert(\"Hello!\");";        ScriptManager.RegisterStartupScript(this, GetType(),                       "ServerControlScript", script, true);    }}

Then in my page I have:

protected override void OnInit(EventArgs e){    base.OnInit(e);    Placeholder1.Controls.Add(new AlertControl());}

Where Placeholder1 is a placeholder in an update panel. The placeholder has a couple of other controls on in it, including buttons.

This behaved exactly as you would expect, I got an alert saying "Hello" every time I loaded the page or caused the update panel to update.

The other thing you could look at is to hook into some of the page lifecycle events that are fired during an update panel request:

Sys.WebForms.PageRequestManager.getInstance()   .add_endRequest(EndRequestHandler);

The PageRequestManager endRequestHandler event fires every time an update panel completes its update - this would allow you to call a method to set up your control.

My only other questions are:

  • What is your script actually doing?
  • Presumably you can see the script in the HTML at the bottom of the page (just before the closing </form> tag)?
  • Have you tried putting a few "alert("Here");" calls in your startup script to see if it's being called correctly?
  • Have you tried Firefox and Firebug - is that reporting any script errors?


When you call ScriptManager.RegisterStartupScript, the "Control" parameter must be a control that is within an UpdatePanel that will be updated. You need to change it to:

ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);