Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 instances of them are on a given form. When more than one control is on the form, I would like exactly 1 reference to the CSS file in the HTML header of the ASP.NET page.

Here is what I have come up with (so far):

Public Sub IncludeStyles(ByVal Page As System.Web.UI.Page)
    'Don't include the reference if it already exists...
    If Page.Header.FindControl("MyID") Is Nothing 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)
    End If
End Sub

Ok, it works...but the obvious flaw here is the use of FindControl() to see if the control exists on the form. Although I am using naming containers and it still seems to be working, I am sure there is some way to break this. Adding another control on the form with the same ID is surely one...

The Question: What is a better way to ensure the header control is only added to the HTML header exactly once?

Note: The ClientScript.RegisterClientScriptResource() method has a parameter that accepts a .NET type and this type can be used to ensure the code is only output once per page. Unfortunately this method only works with JavaScript file references. If there is a built-in equivalent for CSS references, that would be my preference.

Update:

I discovered a slightly more elegant way to do this here by using Page.ClientScript.RegisterClientScriptBlock and telling it you are including your own script tags, however as Rick points out, this doesn't add the script to the html head tag and is also not xhtml compliant.

Update 2:

I saw another interesting idea on this thread, but looping through the controls collection is not a very good solution and adds a lot of overhead if you have several references and several controls on the page.

Chris Lively came up with a better solution that requires less code. Here is my function altered with the new solution:

Public Sub IncludeStyles(ByVal Page As System.Web.UI.Page)
    If Not Page.ClientScript.IsClientScriptBlockRegistered(StyleName) 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("href", cssUrl)
            .Attributes.Add("rel", "stylesheet")
            .Attributes.Add("type", "text/css")
        End With

        Page.Header.Controls.Add(css)
        Page.ClientScript.RegisterClientScriptBlock(GetType(Page), StyleName, "")
    End If
End Sub

A couple of things to note about this solution. In his original post, Chris used the IsClientScriptIncludeRegistered() method which was not the corresponding method to the RegisterClientScriptBlock() method. To make this function correctly, the test must be done with IsClientScriptBlockRegistered().

Also, pay careful attention to the type that is passed to RegisterClientScriptBlock(). I passed a custom datatype to this method (the same across all of my controls), but it didn't register in such a way that the IsClientScriptBlockRegistered() test would work. In order for it to function, the current Page object must be passed in as the Type argument.

Although admittedly this solution feels a bit like a hack, it a) doesn't require a lot of code or overhead, b) produces exactly the desired output on the page, and c) is xhtml compliant code.

like image 553
NightOwl888 Avatar asked Feb 03 '23 01:02

NightOwl888


2 Answers

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.

like image 138
NotMe Avatar answered Feb 06 '23 14:02

NotMe


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;
    }
}
like image 38
Colin Avatar answered Feb 06 '23 16:02

Colin