Just another tech site

Add CSS and Javascript in ASP.NET Header from codebehind

There are several ways to add or modify programatically the generated HTML Header section of an AST.NET page.
Define first a Helper Class

public static void IncludeCSS(Page page, string cssfile)
    HtmlGenericControl child = new HtmlGenericControl("link");
    child.Attributes.Add("rel", "stylesheet");
    child.Attributes.Add("href", cssfile);
    child.Attributes.Add("type", "text/css");
    page.Header.Controls.AddAt(0, child);

public static void IncludeJS(Page page, string jsfile)
     HtmlGenericControl child = new HtmlGenericControl("script");
     child.Attributes.Add("type", "text/javascript");
     child.Attributes.Add("src", jsfile);

public static void IncludeJSScript(Page page, string script)
     HtmlGenericControl child = new HtmlGenericControl("script");
     child.Attributes.Add("type", "text/javascript");
     child.InnerHtml = script;

In the code of an ASP.NET page you will just need to call the different methods.

protected void Page_Load(object sender, System.EventArgs e)
     IncludeCSS(this, "style.css");

Comments on: "Add CSS and Javascript in ASP.NET Header from codebehind" (7)

  1. Very useful! Thanks!

  2. Good work! I had been using src=”> to load dynamic paths but if you do this you cannot add controls to the page dynamically. With your example you can. Great JOB

  3. Remarkable things here. I am very happy to see your article.
    Thanks a lot and I’m having a look forward to contact you. Will you kindly drop me a e-mail?

  4. Spot on with this write-up, I absolutely believe this web site needs a lot more
    attention. I’ll probably be back again to read through more, thanks for the information!

  5. Its such as you read my thoughts! You seem to understand a lot about
    this, such as you wrote the guide in it or something. I feel that you can do with some % to drive the message
    home a bit, but other than that, that is wonderful blog.
    A great read. I will definitely be back.

  6. Hello there! This post could not be written any better! Reading this post
    reminds me of my previous room mate! He always kept chatting about this.
    I will forward this post to him. Pretty sure he will have a good read.
    Many thanks for sharing!

  7. Thank you! From your excellent examples I was able to figure out how to add CSS to the header, too (not an external .css file). You rock!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Tag Cloud

%d bloggers like this: