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

后端 未结 3 1449
粉色の甜心
粉色の甜心 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.

    0 讨论(0)
  • 2020-12-31 15:19

    Why not just create a private boolean variable in the control which you set to true when the CSS is initially created. You can then check this when the method is called to see if the css has already been set. Example below (my VB is rusty so might be slighty wrong)

    Private _hasCss As Boolean = False
    
    Public Sub IncludeStyles(ByVal Page As System.Web.UI.Page)
        'Don't include the reference if it already exists...
        If Not _hasCss Then
            Dim cssUrl As String = Page.ClientScript.GetWebResourceUrl(GetType(Common), StylePath)
    
            Dim css As New System.Web.UI.HtmlControls.HtmlGenericControl("link")
            With css
                .Attributes.Add("rel", "stylesheet")
                .Attributes.Add("type", "text/css")
                .Attributes.Add("href", cssUrl)
                .ID = "MyID"
            End With
    
            Page.Header.Controls.Add(css)
            _hasCss = True
    
        End If
    End Sub
    
    0 讨论(0)
  • 2020-12-31 15:23

    I don't know why, but your solution didn't work for me, the ClientScript.IsClientScriptBlockRegistered call always returned false. But John Bledsoe's suggestion on the link you already provided (here) worked for me:

    public static void IncludeStylesheet(Page page, string href, string styleID)
    {
        //Prevent the stylesheet being included more than once
         styleID = "_" + styleID;
        if (HttpContext.Current.Items[styleID] == null)
        {
            HtmlLink htmlLink = new HtmlLink();
            htmlLink.Href = href;
            htmlLink.Attributes.Add("rel", "stylesheet");
            htmlLink.Attributes.Add("type", "text/css");
            page.Header.Controls.Add(htmlLink);
            HttpContext.Current.Items[styleID] = true;
        }
    }
    
    0 讨论(0)
提交回复
热议问题