Reputation: 2341
I got a user control which implements a reference to a css file, now I want to use this user control many times on page, and this will lead to duplication of inclusion of the css file.
With javascript files it is simple by using the ScriptManager
.
So what is your suggestion for a solution or similar approach to the ScriptManager
?
Upvotes: 2
Views: 771
Reputation: 443
As q is tagged c# thought I may as well paste in c# version from helper class:
public static void AddStyleLink(string href)
{
Page page = (Page)HttpContext.Current.CurrentHandler;
var existing =
(from c
in page.Header.Controls.OfType<HtmlGenericControl>()
where c.Attributes["href"] == href
select c).FirstOrDefault();
if (existing == null)
{
HtmlGenericControl link = new HtmlGenericControl("link");
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("href", href);
page.Header.Controls.Add(link);
}
}
Upvotes: 2
Reputation: 48088
There is no easy way to check if the styles are registered to the page like ClientScript utility.
If you register your styles as an external css file to page like that :
HtmlLink link = new HtmlLink();
link.Href = relativePath;
link.Attributes["type"] = "text/css";
link.Attributes["rel"] = "stylesheet";
Page.Header.Controls.Add(link);
You can then check if it exists by looping the page header's Controls collection and looking for the path of the CSS file.
Upvotes: 1
Reputation: 1634
Here's a technique I've used before, although it may not be the best one:
Dim cssLink As String = String.Format("<link rel='stylesheet' type='text/css' href='{0}/css/cssLink.css' />", Request.ApplicationPath)
If (From c As LiteralControl In Page.Header.Controls.OfType(Of LiteralControl)() Where c.Text = cssLink).Count = 0 Then
Page.Header.Controls.Add(New LiteralControl(cssLink))
End If
Upvotes: 3