Sunday, September 23, 2007

HTML enhancements in ASP.Net 2.0 - PART 2

HTML enhancements in ASP.Net 2.0 - PART 2

PART 1 of this article dealt with accessing head tag in codebehind. This part will deal with some more additional enhancements in 2.0 that is really useful.

Accessing <link tag&rt; :

The link tag is useful to register a CSS file with our Webpage. It can be accessed in codebehind or can be added through codebehind by the following code.

HtmlLink cssLink = new HtmlLink();
cssLink.Href = "StyleSheet.css";
cssLink.Attributes.Add("rel", "stylesheet");
cssLink.Attributes.Add("type", "text/css");
Page.Header.Controls.Add(cssLink);

This will inject a <link&rt; in the html output inside the tag.
<link href="StyleSheet.css" rel="stylesheet" type="text/css" /&rt;
Accessing <Meta&rt; tag :

Meta tags can be used to construct search engine friendly websites, can be used to refresh page and many more. In 2.0 we can achieve this from codebehind through which it gives
the capability to add in runtime.

The following code will do it,

HtmlHead head = (HtmlHead)Page.Header;

HtmlMeta metasearch1 = new HtmlMeta();
HtmlMeta metasearch2 = new HtmlMeta();
metasearch1.Name = "descriptions";
metasearch1.Content = "my personal site";
head.Controls.Add(metasearch1);
metasearch2.Name = "keywords";
metasearch2.Content = "ASP.Net,C#,SQL";
head.Controls.Add(metasearch2);

HtmlMeta metarefresh = new HtmlMeta();
metarefresh.HttpEquiv = "refresh";
metarefresh.Content = "5";
head.Controls.Add(metarefresh);

The following html tag will be injected in the HTML output.

Adding clientside Reset button:

Some time we will need to reset the webpage in clientside which in 2.0 can be done dynamically or in codebehind. The following code will will add a reset input element in the output html.

HtmlInputReset reset = new HtmlInputReset();
reset.ID = "ResetButton";
reset.Value = "Reset";
PlaceHolder1.Controls.Add(reset);

The above code will add a reset tag like below,
<input name="ResetButton" type="reset" id="ResetButton" value="Reset" />

This class is new in 2.0 while this also can be achieved thro HtmlInputButton class in 1.x.