Dynamic meta description and keyword tags for your MasterPages

Posted by Aamir Hasan on ASP.net Weblogs See other posts from ASP.net Weblogs or by Aamir Hasan
Published on Mon, 05 Apr 2010 16:52:00 GMT Indexed on 2010/04/05 16:53 UTC
Read the original article Hit count: 639

Filed under:
|

 Today we're going to look at a technique for dynamically inserting meta tags into your master pages. By taking control of the head tag and inserting your own HtmlMeta you can easily customise these tags.

Might have noticed that when you create a new master page in visual studio your <head> tag gets decorated with a runat="server" attribute.

Asp.net doesn't add this kind of decoration to any other html tags (although you are free to add it if you want). So what makes the head tag special?
By adding the runat="server" you're giving actually converting the control into a HtmlHead control. That doesn't particularly matter for this tutorial other than to note that given a reference to the head control you get all the extras that come with asp.net controls such as access to its controls collection.


The HtmlMeta control lets us wrap up <meta> tags via asp.net code. To add a meta description we need to create an instance, set the name property, the content property, and then add it to the head:

asp.net using (C#)

protected void Page_Init(object sender, EventArgs e)
{
  // Add meta description tag
  HtmlMeta metaDescription = new HtmlMeta();
  metaDescription.Name = "Description";
  metaDescription.Content = "Short, unique and keywords rich page description.";
  Page.Header.Controls.Add(metaDescription);
 
  // Add meta keywords tag
  HtmlMeta metaKeywords = new HtmlMeta();
  metaKeywords.Name = "Keywords";
  metaKeywords.Content = "selected,page,keywords";
  Page.Header.Controls.Add(metaKeywords);
}

asp.net ( VB.NET )

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
  ' Add meta description tag
  Dim metaDescription As HtmlMeta = New HtmlMeta()
  metaDescription.Name = "Description"
  metaDescription.Content = "Short, unique and keywords rich page description."
  Page.Header.Controls.Add(metaDescription)
 
  ' Add meta keywords tag
  Dim metaKeywords As HtmlMeta = New HtmlMeta()
  metaKeywords.Name = "Keywords"
  metaKeywords.Content = "selected,page,keywords"
  Page.Header.Controls.Add(metaKeywords)
End Sub

© ASP.net Weblogs or respective owner

Related posts about ASP.NET

Related posts about seo