asp.net - Alternative to ClientScript.RegisterClientScriptBlock? -


the asp.net function clientscript.registerclientscriptblock can used register chunk of javascript code added page when it's rendered. idea here have multiple instances of various user controls trying register same script on , over, ensures included once.

the problem is, don't have control on where code added page. insert code inside body tag of page, need add (not limited javascript code) head block.

i'm aware of various methods of adding head block via contentplaceholder block or "head.controls.add these options not address problem of same thing being added multiple times.

is there existing way this, or have write class similar clientscript.registerclientscriptblock except targeting head block?

i threw user control. there's nothing in markup @ all, can add new web forms user control project , put in code behind:

public partial class scriptcontrol : system.web.ui.usercontrol {     private dictionary<string, string> _scripts = new dictionary<string, string>(stringcomparer.ordinalignorecase);      public void registerscript(string key, string script)     {         if(!_scripts.containskey(key)) _scripts.add(key, script);     }      protected override void render(htmltextwriter writer)     {         writer.writefullbegintag("script");         foreach(var script in _scripts.values) writer.write(script);         writer.writeendtag("script");     } } 

just add directive page markup:

<%@ register tagprefix="uc" tagname="scriptcontrol"      src="scriptcontrol.ascx" %> 

(where "scriptcontrol.ascx" whatever you've named control) , can add wherever need to, including in header.

<head runat="server">     <uc:scriptcontrol id="headerscriptcontrol" runat="server"/> </head> 

the usage pretty same:

headerscriptcontrol.registerscript("myscript",     @"alert(""hello, world!"")"); 

Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -