Skip to Main Content

Thursday, April 13, 2006

Change Meta Tags Programmatically in ASP.NET 2.0

There is a problem in ASP.NET 2.0. The problem is that when you use MasterPages in an .aspx file, you cannot override the <meta> tags.

The issue that I came across was that I had a <meta name="description"> tag in my MasterPage file for use by search engines. It's nice to display a paragraph saying exactly what you want people to know about a particular page/site. However, if you want to change the description on every page, you are out of luck. Visual Studio 2005 tricked me into thinking it was nice and easy. How?

Well, if you want to change the title of each page that uses a MasterPage, you can specify the title in the @Page directive as follows:

  1. <%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterPage.master"
    CodeFile="default.aspx.cs" Inherits="_default" Title="My Page Title" %>

However, I was tricked into think I could change the meta description because there is a Description attribute in the @Page directive just like title.

To get around this, you must make the change programmatically. There are two ways to do it:
  1. Create a HtmlMeta control for each page, set the properties, and add the control the the page's Header object.

  2. Create a public method in the MasterPage that changes the meta tag and call that method from each page.

Personally, I chose the latter (Number 2) because it was just a little bit less code.

Here's the code:
In the MasterPage.aspx page, I created a <meta> tag in the <head> section:
  1. <meta runat="server" name="description" id="description">

Next, in the MasterPage.aspx.cs file, I created a public method that takes a string parameter and replaces the description with the parameter:
  1. public void ChangeMetaDescription(string description)
  2. {
  3. description.Attributes["content"] = description;
  4. }

Finally, in my .aspx.cs file, I called the ChangeMetaDescription() method in the Page_Load event:
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. MasterPage master = Master as MasterPage;
  4. master.ChangeMetaDescription("This is my new description.");
  5. }

In Conclusion
Although I used this strictly for the meta-description, you can use this method for any control inside the MasterPage.

1 Comments:

At 2:22 PM, Anonymous Anonymous said...

I totally agree about the Description attribute. I foolishly went for some time before realising that setting Description... Doesn't actualy set the description meta tag - madness!

A slight deviation, I used description as a property of my master page.

public string Description
{
set
{
if (value.Length > 200)
{
throw new ArgumentException("Description too long.");
}
description.Attributes["content"] = value;
}
}

 

Post a Comment

<< Home