Pages

Saturday, June 20, 2009

Accessing the Html Header in ASP.NET 2.0

Taking a look at the Page class there is a Header property that looks tempting to be able to do something like dynamically add a stylesheet. The problem is that when you type in Page.Header it doesn't appear that you have full control over the header, even though there is the ever so tempting System.Web.UI.HtmlControls.HtmlHead class. What I had been doing is throwing an id and a runat="server" onto the head tag in my HTML, which I really didn't like because an id tag on the head tag isn't valid XHTML 1.1.

Today, a break through. This has always bothered me, so I took a deeper look and it turns out that Page.Header is defined as IPageHeader. Perhaps, just maybe I could cast Page.Header into System.Web.UI.HtmlControls.HtmlHead. And sure enough, it worked great. Anyways, I feel a little silly about not figuring that out sooner but now that I've gotten this working I feel much better. Anyways, here's some example code to add a stylesheet to a page:

Dim header As Web.UI.HtmlControls.HtmlHead
header = TryCast(Me.Page.Header, Web.UI.HtmlControls.HtmlHead)
If header IsNot Nothing Then
Dim link As New HtmlLink
link.Attributes.Add("href", "~/whatever.css")
link.Attributes.Add("media", "screen")
link.Attributes.Add("rel", "stylesheet")
link.Attributes.Add("type", "text/css")
header.Controls.Add(link)
End If

No comments:

Post a Comment