views:

62

answers:

2

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.

A: 

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
WDuffy
Not gonna work. For one, you made the variable private - meaning that each control instance would have a separate copy. A shared variable would potentially have issues between different users, so that wouldn't work either.
NightOwl888
You're right NightOwl, I totally missed that!
WDuffy
+2  A: 

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.

Chris Lively
Interesting idea, and at first I thought it would work. However, I tried it and there are a couple of problems (unless I have missed something). This registers the CSS under the mime type "text/javascript". In addition, it creates a "script" tag instead of a "link" tag. Third, while not as big of a deal, the tag is not included in the head of the document.
NightOwl888
Oops. Wrong snippet. Look again.
Chris Lively
Great idea! I added a corrected version of this to my original post. The test must be done with RegisterClientScriptBlockInclude, but other than that this code works great.
NightOwl888
@NightOwl888: thanks for finding that. I'm updating our own codebase. I"m surprised it wasn't handled correctly before..;)
Chris Lively