Search This Blog

Wednesday, October 6, 2010

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

Programmer Question

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.



Find the answer here

No comments:

Post a Comment

Related Posts with Thumbnails