Examples of link tags are:
Stylesheets, Rss Feeds, Favorite Icons etc.
To add one of these tags, you need to use the System.Web.UI.HtmlControls.
HtmlLink class.
HtmlLink stylesheet = new HtmlLink();
stylesheet.Attributes.Add("href", "style.css");
stylesheet.Attributes.Add("rel", "stylesheet");
stylesheet.Attributes.Add("type", "text/css");
Page.Header.Controls.Add(stylesheet);
Which renders as:
<link href="style.css" rel="stylesheet" type="text/css" />
To make this more versatile, we can wrap that up into a "StyleSheet" class.
public class StyleSheet : HtmlLink
{
public StyleSheet(string styleSheet)
{
this.Attributes.Add("href", styleSheet);
this.Attributes.Add("rel", "stylesheet");
this.Attributes.Add("type", "text/css");
}
}
We can then instantiate as many of these as we need, for example:
Page.Header.Controls.Add(new StyleSheet("/styles/site.css"));
Page.Header.Controls.Add(new StyleSheet("/styles/user.css"));
Another useful tag to be able to add programmatically is the Base tag.
For those of you who don't know, the base tag essentially tells the browser to treat any url requests to start at the location set in the base tag.
This came in useful for me when I was setting up the url rewriting that happens on this site as I didn't need to add any special logic to work out where my images or styles directories were relative to the path the browser thinks it needs to look at. The main place this is useful is in my blog where if you request /blog/2008/04 you are not actually going to a directory called blog/2008/04 but if you just asked the browser to get /images/picture.gif it would ask for /blog/2008/04/images/picture.gif whereas with the base tag set to tr3v.net it will ask for tr3v.net/images/picture.gif.
For this, we need to inherit from a different class. System.Web.UI.HtmlControls.HtmlGenericControl
public class BaseTag : HtmlGenericControl
{
public BaseTag() : base("base")
{
this.Attributes.Add("href", HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Host + "/");
}
}
Since the base tag needs to be defined before any code that refers to a relative location on your site, the best thing is to use Page.Header.AddAt() to place it first in the head tag.
Page.Header.Controls.AddAt(0, new Tr3v.Net.HtmlControls.BaseTag());
Although you can just type a <base> tag in the head of your master page, this will work with any domain. For example this works on my local test server "http://gandalf" and on my live site "http://tr3v.net" without having to change anything.
HtmlGenericControl should be used when you want a html tag with a closing tag. (Note: C# 3.0 syntax used)
| C# Code |
Rendered HTML |
HtmlGenericControl h3 = new HtmlGenericControl("h3"); h3.Controls.Add(new Literal { Text = "hello" }); |
<h3>hello</h3> |
This article was published on the 9th April 2008