简体   繁体   中英

Alternative to ClientScript.RegisterClientScriptBlock?

The ASP.NET function ClientScript.RegisterClientScriptBlock can be used to register a chunk of JavaScript code that will be added to the page when it's rendered. The idea here is that you could have multiple instances of various user controls trying to register the same script over and over, but this ensures that it will only be included once.

The problem is, you don't really have any control over where the code is added to the page. This will insert the code inside the BODY tag of your page, but I need to add something (not limited to JavaScript code) into the HEAD block.

I'm well aware of various methods of adding something to the HEAD block via a ContentPlaceHolder block or by "Head.Controls.Add but these options do not address the problem of the same thing being added multiple times.

Is there an existing way to do this, or do I have to write a class that does something similar to ClientScript.RegisterClientScriptBlock except targeting the HEAD block?

I threw together a user control. There's nothing in the markup at all, so you can just add a new Web Forms User Control to your project and put this in the 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 the directive to your page markup:

<%@ Register TagPrefix="uc" TagName="ScriptControl" 
    Src="ScriptControl.ascx" %>

(where "ScriptControl.ascx" is whatever you've named the control) and then you can add it wherever you need to, including in the header.

<head runat="server">
    <uc:ScriptControl id="HeaderScriptControl" runat="server"/>
</head>

The usage is pretty much the same:

HeaderScriptControl.RegisterScript("myScript",
    @"alert(""hello, world!"")");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM