Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Using Meta Tags with Master Pages in ASP.NET

0.00/5 (No votes)
24 May 2007 2  
Extend the @Page directive so that you can specify meta keywords and meta descriptions on content pages.

Introduction

The Master Pages introduced in ASP.NET 2.0 are a great feature, however, they don't provide a good way to perform the most basic search engine optimization. If you want your web pages to be listed properly and ranked well in search engines, then you need to specify good titles and meta tag descriptions on each page. This article explains how to extend the @Page directive on your ASP.NET pages so that you can specify the meta tag description and meta tag keywords on each content page when using master pages.

Background

When optimizing your web pages for search engines, some of the most important elements on the page are the <title> tag and the description meta tag. The <title> and meta tags are usually specified in the <head> section of the HTML on each page as seen in the example below from the Rhinoback online backup site:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>
   Rhinoback Professional Secure Online Backup Services for Small 
   and Medium Business - SMB
</title>
<meta name="description" content="Professional Online Backup Services. 
      Rhinoback provides robust backup functionality at affordable prices.  
      Premium features, premium services, low prices.  Get the most for 
      your money with Rhinoback!" />
<meta name="keywords" content="backup, online backup, secure backup, 
      cheap backup, free backup, offsite backup,internet backup, 
      secure files, offsite data storage, privacy, security, features, 
      low prices, premium service, remote backup" />
</head>
<body>
     <!-- page content -->
</body>
</html>

The text from the <title> tag is displayed at the top of most browsers. See the title of the Internet Explorer window in the example below:

Sample of Rhinoback page with title tag

The meta description text is displayed by the search engine when your page is listed. The example below is from a Google search. The text below the underlined title comes directly from the meta description tag. Without a meta description tag, your page may be listed with a description that was extracted from text found somewhere on the page. It is always better to specify the text for the description of each page rather than leave it up to a search engine robot.

Master Pages were introduced in ASP.NET 2.0 and have proven to be a valuable feature. This article does not attempt to explain the details of master pages or how to implement them, that is well covered in numerous other articles. When using master pages the <head> section is part of the master page and is automatically included on all of the content pages. Fortunately the developers at Microsoft included the Title attribute on the @Page directive that enables the developer to specify the title of the page on the content pages rather than on the master page.

<%@ Page Language="C#" MasterPageFile="~/PageTags.master" 
    AutoEventWireup="true" CodeFile="home.aspx.cs" Inherits="home" 
    Title="My home page title" %>

The @Page directive above is from a content page in an ASP.NET 2.0 website that uses a master page. As discussed above, you may need to specify some meta tags at the content page level rather than at the master page level. You may have discovered that the @Page directive does have a Description attribute, however, it does not create a meta description tag for your page. In fact, anything that you specify on the Description attribute is completely ignored and not used for anything.

In my case, it was completely unacceptable to have the same description on all pages of my site. I also wanted to specify keywords for each page that may vary from page to page. My first cut at a solution to this problem involved using the code-behind to insert the desired meta tags onto each pages' <head> section as shown in the Page_Load method of a content page below:

C#

    protected void Page_Load(object sender, EventArgs e)
    {
            HtmlMeta tag = new HtmlMeta();
            tag.Name = "description";
            tag.Content = "My description for this page";
            Header.Controls.Add(tag);
    }

VB

    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            Dim tag As HtmlMeta = New HtmlMeta()
            tag.Name = "description"
            tag.Content = "My description for this page"
            Header.Controls.Add(tag)
    End Sub

The problem with this solution is that the title of the page, the meta description, and the content of a page are all related and I really want the title and description to be together and also in the same ASPX file as the content. The Page_Load method can easily be placed within <script> tags on the ASPX page, but I wanted to find a solution that was easier to maintain and would allow for quick and easy inspection of the tags on each page.

The following solution meets my objectives by extending the @Page directive to include the meta tags that I want to specify for each page individually.

Solution

I created a base page class that inherits from System.Web.UI.Page and then I modified my content pages to inherit from my BasePage class. The BasePage class contains the code that adds the meta tags to the header controls collection on the page. Since all of my content pages are inheriting from BasePage, this code only needs to exist in one place and not on every page.

C#

/* ********************************************** 
 * Page directive extender - base page class    *
 *  by Jim Azar - http://www.rhinoback.com      *
 * **********************************************/

using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

/// <SUMMARY>

/// Base class with properties for meta tags for content pages 

/// </SUMMARY>

public class BasePage : Page
    {
    private string _keywords;
    private string _description;
    // Constructor

    // Add an event handler to Init event for the control

    // so we can execute code when a server control (page)

    // that inherits from this base class is initialized.

    public BasePage()
        {
        Init += new EventHandler(BasePage_Init);
        }

    // Whenever a page that uses this base class is initialized

    // add meta keywords and descriptions if available

    void BasePage_Init(object sender, EventArgs e)
        {

        if (!String.IsNullOrEmpty(Meta_Keywords))
            {
            HtmlMeta tag = new HtmlMeta();
            tag.Name = "keywords";
            tag.Content = Meta_Keywords;
            Header.Controls.Add(tag);
            }

        if (!String.IsNullOrEmpty(Meta_Description))
            {
            HtmlMeta tag = new HtmlMeta();
            tag.Name = "description";
            tag.Content = Meta_Description;
            Header.Controls.Add(tag);
            }
        }

    /// <SUMMARY>

    /// Gets or sets the Meta Keywords tag for the page

    /// </SUMMARY>

    public string Meta_Keywords
        {
        get 
            { 
            return _keywords; 
            }
        set 
            { 
            // strip out any excessive white-space, newlines and linefeeds

            _keywords = Regex.Replace(value, "\\s+", " "); 
            }
        }

    /// <SUMMARY>

    /// Gets or sets the Meta Description tag for the page

    /// </SUMMARY>

    public string Meta_Description
        {
        get 
            { 
            return _description; 
            }
        set 
            {
            // strip out any excessive white-space, newlines and linefeeds

            _description = Regex.Replace(value, "\\s+", " "); 
            }
        }
    }

VB

'* ********************************************** 

'* Page directive extender - base page class    *

'*  by Jim Azar - http://www.rhinoback.com      *

'* **********************************************/


Imports System
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Text.RegularExpressions


' Base class with properties for meta tags for content pages 


Public Class BasePage
    Inherits Page

    Dim _keywords As String
    Dim _description As String
    ' Constructor

    ' Add an event handler to Init event for the control

    ' so we can execute code when a server control (page)

    ' that inherits from this base class is initialized.

    Public Sub New()
        AddHandler Init, New EventHandler(AddressOf BasePage_Init)
    End Sub

    ' Whenever a page that uses this base class is initialized

    ' add meta keywords and descriptions if available

    Sub BasePage_Init(ByVal sender As Object, ByVal e As EventArgs)

        If Not String.IsNullOrEmpty(Meta_Keywords) Then
            Dim tag As HtmlMeta = New HtmlMeta()
            tag.Name = "keywords"
            tag.Content = Meta_Keywords
            Header.Controls.Add(tag)
        End If

        If Not String.IsNullOrEmpty(Meta_Description) Then
            Dim tag As HtmlMeta = New HtmlMeta()
            tag.Name = "description"
            tag.Content = Meta_Description
            Header.Controls.Add(tag)
        End If
    End Sub


    'Gets or sets the Meta Keywords tag for the page

    Public Property Meta_Keywords() As String
        Get
            Return _keywords
        End Get
        set 
            ' strip out any excessive white-space, newlines and linefeeds

            _keywords = Regex.Replace(value, "\\s+", " ")
        End Set
    End Property


    ' Gets or sets the Meta Description tag for the page

    Public Property Meta_Description() As String
        Get
            Return _description
        End Get
        Set(ByVal value As String)
            ' strip out any excessive white-space, newlines and linefeeds

            _description = Regex.Replace(value, "\\s+", " ")
        End Set
    End Property
End Class

The Meta_Keywords and Meta_Description properties are public and can be set when the class (or derived class) is instantiated. When a page that inherits from this class is initialized, the Base_Init event handler is invoked and adds the meta tags to the page.

On each content page, simply change the inheritance so that they inherit from BasePage instead of page or System.Web.UI.Page. See below:

C#

public partial class home : BasePage 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

VB

Partial Class home
    Inherits BasePage
    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    
    End Sub
End Class

Now that each content page is inheriting from BasePage, they have the properties and the code to insert the meta tags. Now we can specify the Meta_Keywords and Meta_Description values on the @Page directive on the ASPX file. See the examples below:

<%@ Page Language="C#" MasterPageFile="~/PageTags.master" 
  AutoEventWireup="true" CodeFile="home.aspx.cs" Inherits="home" 
  CodeFileBaseClass="BasePage" 
  
  Title="My home page title" 
  
  Meta_Keywords="page directive, extension, dotnet, asp.net"
                              
  Meta_Description="This is the meta description for my home page."          
%>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" 
    Runat="Server">
    <h3>My home page content<h3>
    <p>
    This is the content on my home page.  This page has an appropriate title
    tag and also has meta tags for keywords and description that are 
    relative to this page. The title tag is essential to good search engine 
    optimization and the meta description is the text that the search engine
    will display when your page is listed in search results.  The title and 
    meta description should be set specific to each page and should describe
    the content of the page. 
    </p>
</asp:Content>

Note the addition of the CodeFileBaseClass attribute. This is required so that page can reference the public properties specified in the BasePage class.

Points of Interest

You may have noticed the regular expression in the BasePage class. This is here so that you can break the description and keyword tags up onto mulitple lines in your ASPX file, making them more readable and maintainable. Consider the following example from the IdeaScope Customer Feedback Management website:

<%@ Page Language="C#" MasterPageFile="~/IdeaScope.master" 
  AutoEventWireup="true" CodeFile="is.aspx.cs" Inherits="_is"
  CodeFileBaseClass="BasePage" 
  
  Title="Effective Customer Feedback Management, 
      Improve Customer Commmunication" 
  
  Meta_Keywords="Customer Feedback, Customer Opinion, feedback, opinion,
       idea, ideas, idea management, customer feedback management,         
        product management, product manager, product marketing,         
        product marketing manager"
                              
  Meta_Description="IdeaScope is an on-demand and embedded solution that 
       allows you to capture, prioritize and centrally manage customer 
       feedback. Make your customer feedback process more efficient. Save 
       time and involve more stakeholders without significant cost." 
  %>

Without the regular expression replacement, these tags would contain new lines and excess spaces at the beginning and ending of each line. I suspect that some search engine spiders might get upset about that, and the primary reason for including these tags is to make search engines happy.

There is one last thing that you might want to do to tidy up this solution. The ASP.NET validation in Visual Studio 2005 is not going to recognize Meta_Keywords or Meta_Description. You will get warnings from the compiler saying that these are not valid attributes for the @Page directive. You will also see those red squiggley lines under those attributes in Visual Studio. Your code will compile and run fine. If you are like me and don't want to see any warnings or validation errors, then you will want to add the following lines to Visual Studio's schema for the @Page directive.

  <xsd:attribute name="Meta_Keywords" vs:nonfilterable="true" />
  <xsd:attribute name="Meta_Description" vs:nonfilterable="true" />

These nodes should be inserted as child nodes of <xsd:complexType name="PageDef"> The schema file is located at the following location if you installed Visual Studio 2005 in the default location:

C:\Program Files\Microsoft Visual Studio 8\Common7\Packages\schemas\html\page_directives.xsd

This article demonstrates how to extend the @Page directive to support meta keywords and meta descriptions. You can easily add other meta tags to the sample code. Complete source files and a sample project are included for C# and VB. Thanks to Scott Guthrie's blog post, Obsure but cool feature in ASP.NET 2.0 for the information that led up to this solution.

Your comments and suggestions to improve this article are welcome.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here