Set HTML header items programmatically in ASP.NET 2.0

by Mads Kristensen 19. October 2006 01:15

Among the differences between version 1.1 and 2.0 of .NET Framework is the many new controls. Even though most of them don’t add new functionality they make a lot of things much easier and cleaner than before. Some of these new controls in ASP.NET are the HTML controls HtmlHeadHtmlMeta and HtmlLink.

They don’t add much new functionality by them selves, but look at how clean the code becomes when you use them:

protected void Page_Load(object sender, EventArgs e)

{

  AddMetaContentType();

  AddMetaTag("keywords", "word1, word2, word3...");

  AddMetaTag("description", "bla bla bla");

  AddStyleSheet("/includes/style.css");

}

 

private void AddMetaContentType()

{

  HtmlMeta meta = new HtmlMeta();

  meta.HttpEquiv = "content-type";

  meta.Content = Response.ContentType + "; charset=" + Response.ContentEncoding.HeaderName;

  Page.Header.Controls.Add(meta);

}

 

private void AddMetaTag(string name, string value)

{

  HtmlMeta meta = new HtmlMeta();

  meta.Name = name;

  meta.Content = value;

  Page.Header.Controls.Add(meta);

}

 

private void AddStyleSheet(string relativePath)

{

  HtmlLink link = new HtmlLink();

  link.Href = relativePath;

  link.Attributes["type"] = "text/css";

  link.Attributes["rel"] = "stylesheet";

  Page.Header.Controls.Add(link);

}

This is much more cleaner than adding literal controls to the page header or whatever trick you used before. Just remember to add a runat="server" attribute to the <head> tag of your web page.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

ASP.NET

Comments

10/24/2006 3:38:38 PM #

 Andreas Kraus

Good post Mads, thanks for the tip.

Andreas Kraus |

10/25/2006 4:34:45 AM #

 Nandu

Very nice.
I was wondering if there a way to add .js file programatically?
Currently, I am using literal conrol and passing the script tag with the .js path.

Any ideas?

Nandu |

10/25/2006 4:47:43 AM #

Mads Kristensen

Nandu, even though there is no script control in .NET 2.0, you can use an HtmlGenericControl to achieve the same like this:

private void AddJavaScript(string relativePath)
{
  HtmlGenericControl script = new HtmlGenericControl("script");
  script.Attributes["type"] = "text/javascript";
  script.Attributes["src"] = relativePath;
  Page.Header.Controls.Add(script);
}

Mads Kristensen |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008