How to add Html Headers programmatically
Have you ever wanted to programmatically add html headers to your ASP.Net page? I needed to do this when working on HeadTreez.com and learned to use the System.Web.UI.HtmlControls.HtmlHead object of the page. Using this, we are able to inject the user's settings into the page's:
- title
- CSS link (our default styles)
- CSS in-page styles (the site's override styles)
- description
- keywords
Originally, I accomplished this by putting server side script blocks in the header that would pull the values, but that wasn't ideal so I decided to take care of everything in the code-behind. (Gotcha --> ) One thing I learned really quick was that you have to remove all script blocks from the header to be able to write header objects programatically from the code-behind page.
So I've built a function that you can pass the title, css link, css in-page string, description, and keywords. This function will be very happy to ignore empty values or null values and just move on to the next item and try to put it in.
- protected
void AddHeaders(string Title, string Desc, string Keywords,string CssLink, string Css)
{
try
{
HtmlHead myHeader = (HtmlHead)this.Page.Header;
if (myHeader != null)
{
//Add base CSS sheet
if(CssLink != null && CssLink.Length > 0)
{
HtmlLink myLink = new HtmlLink();
myLink.Attributes.Add("href", CssLink);
myLink.Attributes.Add("rel", "stylesheet");
myLink.Attributes.Add("type", "text/css");
myHeader.Controls.Add(myLink);
}
if (Title != null && Title.Length > 0)
{
HtmlTitle myTitle = new HtmlTitle();
myTitle.Text = Title;
try
{
/*not sure if this the best way to remove the old title, but works in my case*/
myHeader.Controls.Remove(this.Page.Header.Controls[0]);
myHeader.Controls.Add(myTitle);
}
catch
{ }
}
if (Desc != null && Desc.Length > 0)
{
HtmlMeta myDesc = new System.Web.UI.HtmlControls.HtmlMeta();
myDesc.Attributes.Add("name", "description");
myDesc.Attributes.Add("content", Desc);
myHeader.Controls.Add(myDesc);
}
if (Keywords != null && Keywords.Length > 0)
{
HtmlMeta myKw = new System.Web.UI.HtmlControls.HtmlMeta();
myKw.Attributes.Add("name", "keywords");
myKw.Attributes.Add("content", Keywords);
myHeader.Controls.Add(myKw);
}
//Add customized CSS
if (Css != null && Css.Length > 0)
{
Literal litCss = new Literal();
litCss.Text = "<style type=" + '"' + "text/css" + '"' + ">" + Css + "</style>";
myHeader.Controls.Add(litCss);
}
}
}
catch
{
//Handle your unexpected error.
}
}
Hope it helps you do this a little quicker than I did.
-Marc Talcott
[ 1/11/2007 ]