ASP.NET gives you the opportunity to add script blocks and JavaScript includes
at runtime using methods like
ClientScriptManager.RegisterClientScriptInclude()
.
How to perform a similar action to include style sheets?
There's no native method, but it's quite simple to perform: we're going to
use the HtmlLink
control.
HtmlLink link =
new
HtmlLink();
link.Href =
"./MyFolder/MyStyleSheet.css"
;
link.Attributes.Add(
"type"
,
"text/css"
);
link.Attributes.Add(
"rel"
,
"stylesheet"
);
Page.Header.Controls.Add(link);
An interesting parameter of the
ClientScriptManager.RegisterClientScriptInclude()
method is the Key,
that's used to assure you do not add the same include twice.
How to perform the same thing with the previous code?
The solution is to give the control a unique id:
public
void
AddStyleLink(String Key, String StyleUrl)
{
if
(!String.IsNullOrEmpty(Key))
if
(Page.Header.FindControl(Key) !=
null
)
return
;
HtmlLink link =
new
HtmlLink();
if
(!String.IsNullOrEmpty(Key)) link.ID = Key;
link.Href = StyleUrl;
link.Attributes.Add(
"type"
,
"text/css"
);
link.Attributes.Add(
"rel"
,
"stylesheet"
);
Page.Header.Controls.Add(link);
}
Did you find this article useful?
Please help us to spread it over the web using Twitter.
You have only to press the button here below!