Wednesday, January 11, 2006

Dynamically Add a Stylesheet Reference to a MasterPage

Today I was having a little problem with ASP.NET 2.0. My site uses a Master Page and a couple of .css files. The problem was that I wanted one stylesheet to be used on the whole site, and an additional stylesheet to be used on one page. The problem was that in a child page I couldn't find a way to add an HTML link element, since the page's head section was outside of the content.

What I ended up doing was adding a public method in the Master Page that I could call in the child's Load event to add a stylesheet reference. It seems to work well so far. I don't know if this is the best approach, but I couldn't find much else out there.

Here are the details:

MyMasterPage.master is the site-wide master page, in it you will need to add an id to the <head /> element so you can get to it in the code behind:

<head id="MyMasterPageHead" runat="server">

 

 

 


In the code behind of MyMasterPage you will need to add the following method:

Partial Class MyMasterPage

  Inherits System.Web.UI.MasterPage

 

  Public Sub AddStyleSheetLink(ByVal fileName As String)

    Dim stylesheetLink As New HtmlLink

    With stylesheetLink

      .Attributes("href") = fileName

      .Attributes("type") = "text/css"

      .Attributes("rel") = "stylesheet"

    End With

 

    MyMasterPageHead.Controls.Add(stylesheetLink)

 

  End Sub

End Class

 

 

 


Then on your content page, just add the following to the Page.Load event:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

  CType(Master, MyMasterPage).AddStyleSheetLink("ContentStyle.css")

End Sub

 


Notice that you need to cast the Page's master to the MyMasterPage type so you can call the AddStyleSheetLink() method.

That's it!

3 comments:

Sam said...

can you show a c# example as well?

SHOVEL said...

Why not just use:
----------------------------------
If Not (IsPostBack) Then
Dim stylesheetLink As New HtmlLink
With stylesheetLink
.Attributes("href") = "MyStyleSheet.css"
.Attributes("type") = "text/css"
.Attributes("rel") = "stylesheet"
End With
Page.Header.Controls.Add(stylesheetLink)
End If
-----------------------------------
in the child page's load event?

lance said...

@shovel,

That method works great too! If you are going to be doing this on a bunch of pages though, it might be nice to have the method available in the masterpage. However, with your approach, you don't have to update the masterpage and maybe you don't want to.

In VS2008, there is a new default template for masterpages, and I like it better. There is a second <asp:ContentPlaceHolder /> element in the head. With this you can add the stylesheet link right in the markup. You can do this in VS2005 as well. The editor will show an error on the asp element in head, but it will compile and run as expected.