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
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.
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
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;
}
}