ScriptManager adding script multiple times to page (duplicates)

Jamie Treworgy picture Jamie Treworgy · Dec 3, 2010 · Viewed 9.7k times · Source

This is the exact same question as this unanswered one from May.

(edit) Note: this unanswered post exactly describes the behavior - extra scripts being added in the <head> by ScriptManager.RegisterClientScriptBlock in a usercontrol, in an UpdatePanel, is causing duplicates. C# .NET 4.0. The page is structured like this:

MasterPage
   Page
      UserControl1 (ascx) - loaded in code by Page
         UpdatePanel
            UserControl2 (ascx) - loaded in code by UserControl1

The first time the script is added as expected, in the body. The code, simply, in the UserControl2 OnInit:

ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "myscript", script, true);

I've also tried referencing "this" instead of page, which doesn't really make sense since I don't want the same script keys duplicated on the page if the usercontrol is loaded multiple times on a page, but it didn't work anyway.

After a partial postback, the script is added again - but curiously in the <head> of the page, not the body, and interestingly, lacking the normal //<![CDATA[...//]]> wrapper that asp.net usually adds.

Another script which is added by UserControl1 is duplicated exactly the same way after a partial postback.

Does anyone know why this is happening?

Answer

jvanrhyn picture jvanrhyn · Dec 3, 2010

You can add a check to confirm if the script has been registered before registering it again.

if (!Page.ClientScript.IsClientScriptRegistered (Page.GetType(), "myscript"))
   ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "myscript", script, true);

I hope this helps.