24
votes

I have used code like this in the past to successfully pop up an alert message on my asp.net webpage. Now it is not working. I can't figure out why.

ScriptManager.RegisterStartupScript(this, typeof(Page), UniqueID, 
     "alert('This pops up')", true);

Any ideas?

4
I tried ScriptManager.RegisterStartupScript(this, typeof(Page), "12344", "alert('This pops up')", true); and it worked perfectly fine for me. Check the Source of page to see if its emitting the code and if that is fine.rsapru
It's because registering a script with ScriptManager is only registering. You need something to fire it off, like a button onclick eventFandango68

4 Answers

43
votes

Off the top of my head:

  • Use GetType() instead of typeof(Page) in order to bind the script to your actual page class instead of the base class,
  • Pass a key constant instead of Page.UniqueID, which is not that meaningful since it's supposed to be used by named controls,
  • End your Javascript statement with a semicolon,
  • Register the script during the PreRender phase:

protected void Page_PreRender(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this, GetType(), "YourUniqueScriptKey", 
        "alert('This pops up');", true);
}
24
votes

Try this code...

ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "script", "alert('Hi');", true);

Where UpdatePanel1 is the id for Updatepanel on your page

1
votes

You must put the updatepanel id in the first argument if the control causing the script is inside the updatepanel else use the keyword 'this' instead of update panel here is the code

ScriptManager.RegisterStartupScript(UpdatePanel3, this.GetType(), UpdatePanel3.UniqueID, "showError();", true);
0
votes

I came across a similar issue. However this issue was caused because of the way i designed the pages to bring the requests in. I placed all of my .js files as the last thing to be applied to the page, therefore they are at the end of my document. The .js files have all my functions include. The script manager seems that to be able to call this function it needs the js file already present with the function being called at the time of load. Hope this helps anyone else.