Search code examples
javascriptasp.netscriptmanager

ScriptManager.RegisterStartupScript code not working - why?


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?


Solution

  • 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);
    }