Accessing the Html Header in ASP.NET 2.0

I feel a bit silly for not figuring this out quicker, so hopefully I can redem myself by posting this to help people out.  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

19 Comments

  • Wow, what a nice trick. I too didn't find that before. I will definitely have an use for that! :)

  • so ohw exactly can i do this can u plz send me the instructions step by step

  • Um, step by step instructions would be:

    1) take code I posted and paste it in page_load or something

    2) finished.

  • If you want to do it with a tag which does not have a .NET implementation, you can use a generic object:

    Dim script As New HtmlGenericControl("script")
    script.Attributes.Add("type", "text/javascript")
    script.Attributes.Add("src", urlbase & "js/validate.js")
    Me.Header.Controls.Add(script)

  • If you want to generate CSS on the fly and add it as embedded in the page output HTML you can try this (C#):

    string myCss = "body{ background-color: black; }"
    string cssStyle = "" + myCss + "";

    Literal cssLiteral = new Literal();
    cssLiteral.Text = cssStyle;

    Page.Header.Controls.Add(cssLiteral);

  • I want to add Templates in My WebSites. But I got Comfused after lot muh try.

  • Thank a lot for that post, I was using the runat="server" thing in the header and I never liked it.

    @Rob siklos

    A method to add dynamically an include to a javascript file exists.
    Use that in the Page_Load :
    Page.ClientScript.RegisterClientScriptInclude( "aKeyToIdentifyIt", "./Script/MyScriptFile.js");

    It's bit easier ;)

  • What am I missing here? Don't you still have to put a runat="server" statement in the tag? I get no instance of Page.Header without a runat="server" statement. Therefore, the statements in your If/Then loop never execute.

  • It's the fact you don't have to put an ID in, the runat="server" has to stay.

  • hi please replay heade manu how to call other page in the forms

  • Really fruitful trick. This makes my life easy :-)

  • wow .. this is great!!!

  • "but now that I've gotten this working"

    gotten is such a horrible word, makes you sound like a moron. If you need to flesh out this phrase then why not "but now I have this working"...

  • Or in a real language ;)

    HtmlHead header = this.Page.Header as HtmlHead;
    if (header != null)
    {
    HtmlLink link = 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);
    }

  • hello,
    HtmlLink lnkHeade = new HtmlLink();
    lnkHeade.Attributes.Add("rel", "shortcut icon");
    lnkHeade.Attributes.Add("href", "../Images/Favorites/Classic car yellow.ico");
    Page.Header.Controls.Add(lnkHeade);

    I have used this, but its not working in IE8, please help me out

  • Wow thanks! This really did help, thankyou so much! This is great if you are creating an application with themes such as myself, so you can dynamically insert css.

  • i
    want to link my page content at a link bar


  • Genial entrada me encanta tu manera de escribir. He leído rápidamente sus mensajes y puedo ver que su sitio web tiene un potencial enorme para ayudar a muchas personas que buscan este tipo de soluciones. Sin embargo todos los que trabamos en internet tenemos necesidades para mejorar nuestros negocios y esta es una buena manera de hacerlo.

    Gracias por dejarme escribir aqui en su pagina.!

  • I am very glad that I found this web blog, exactly the right information that I was searching for! Thanks. Best regards.

Comments have been disabled for this content.