ASP.NET Custom Control - What is the best way to include embedded CSS reference only once?

后端 未结 3 1464
粉色の甜心
粉色の甜心 2020-12-31 15:08

The problem: I am embedding a CSS file into a custom control library with several controls. I want to share the same CSS file for all of the controls regardless of how many

3条回答
  •  春和景丽
    2020-12-31 15:08

    To prevent duplication when emitting css files from server controls, we do the following:

    if (!Page.ClientScript.IsClientScriptBlockRegistered("SoPro." + id)) {
        HtmlLink cssLink = new HtmlLink();
        cssLink.Href = cssLink.Href = Page.ClientScript.GetWebResourceUrl(this.GetType(), styleSheet);
        cssLink.Attributes.Add("rel", "stylesheet");
        cssLink.Attributes.Add("type", "text/css");
        this.Page.Header.Controls.Add(cssLink);
        this.Page.ClientScript.RegisterClientScriptBlock(typeof(System.Web.UI.Page), "SoPro." + id, String.Empty);
    }
    

    First we test to see if the named script was previously registered. If not, we add it in.

提交回复
热议问题