Sometimes the need arises to have the ability to change the meta tags within a child of a master page. I created a couple public properties that you can put in your code behind for your .net 2.0 master page to change the keywords and description meta tags on the fly. The methods below will set the tags and replace them if they already exist. Code is in C#.
Description Meta Tag
public string Description
{
set
{
if (Page.Header.FindControl(“dsc”) == null)
{
HtmlMeta hmDesc = new HtmlMeta();
hmDesc.Name = “description”;
hmDesc.ID = “dsc”;
hmDesc.Content = value;
Page.Header.Controls.Add(hmDesc);
}
else
{
((HtmlMeta)Page.Header.FindControl(“dsc”)).Content = value;
}
}get
{
HtmlMeta hmDesc = (HtmlMeta)Page.Header.FindControl(“dsc”);
return (hmDesc != null) ? hmDesc.Content : String.Empty;
}
}
Keywords Meta Tag
public string Keywords
{
set
{
if (Page.Header.FindControl(“kw”) == null)
{
HtmlMeta hm = new HtmlMeta();
hm.Name = “keywords”;
hm.ID = “kw”;
hm.Content = value;
Page.Header.Controls.Add(hm);
}
else
{
((HtmlMeta)Page.Header.FindControl(“kw”)).Content = value;
}}
get
{
HtmlMeta hm = (HtmlMeta)Page.Header.FindControl(“kw”);
return (hm != null) ? hm.Content : String.Empty;
}
}
Here are other ways that you can insert headers from the page level as well. The “ResolveUrl” methods below will get the relative path from the .net web application to whatever you pass it so a tilde will be translated into the root of your application. This function is really handy too.
Insert JavaScript Link
HtmlGenericControl js = new HtmlGenericControl();
js.TagName = “script”;
js.Attributes.Add(“language”, “javascript”);
js.Attributes.Add(“type”, “text/javascript”);
js.Attributes.Add(“src”, ResolveUrl(“~/js/global.js”));
/* ResolveUrl will get the relative path from the .net web application */
this.Page.Header.Controls.Add(js);
Cascading Style Sheet Link
HtmlLink ss = new HtmlLink();
ss.Attributes.Add(“type”, “text/css”);
ss.Attributes.Add(“rel”, “stylesheet”);
ss.Attributes.Add(“href”, ResolveUrl(“~/css/scr.css”));
this.Page.Header.Controls.Add(ss);
Robots/Other Meta Tags
HtmlMeta hm = new HtmlMeta();
hm.Name = “robots”;
hm.Content = “index,follow”;
this.Page.Header.Controls.Add(hm);//and re-use the HtmlMeta object again
hm = new HtmlMeta();
hm.Name = “date”;
hm.Content = DateTime.Now.ToString(“yyyy-MM-dd”);
hm.Scheme = “YYYY-MM-DD”;
this.Page.Header.Controls.Add(hm);
As you can see, the new meta functionality of .net 2.0 is a lot better than 1.1. Hopefully this will be of use in some of your web applications.