Click here to Skip to main content
15,881,757 members
Articles / Web Development / ASP.NET
Article

Using Meta Tags with Master Pages in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.84/5 (52 votes)
24 May 2007CPOL6 min read 425.1K   3.1K   121   102
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
<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.

Image 2

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.

HTML
<%@ 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#

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

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#

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

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#

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

    }
}

VB

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:

HTML
<%@ 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:

HTML
<%@ 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.

XML
<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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHTMLMETA Class for ASP CLassic Pin
BjorgenEatinger23-Apr-20 11:36
professionalBjorgenEatinger23-Apr-20 11:36 
QuestionHoneypots - ignore this Pin
Jim Azar9-May-19 13:56
Jim Azar9-May-19 13:56 
QuestionNeed a little more help on this please Pin
Rachel828-May-15 9:45
Rachel828-May-15 9:45 
Questionusing meta tag with master page Pin
sanjoysharan20-Mar-13 18:30
sanjoysharan20-Mar-13 18:30 
QuestionNice Article Pin
Pavan Navule8-Jul-12 5:02
Pavan Navule8-Jul-12 5:02 
QuestionApp_Code folder not working online. Pin
Pagem197222-May-12 4:20
Pagem197222-May-12 4:20 
QuestionMasterPage Keywords Pin
corprosystems26-Mar-12 6:01
corprosystems26-Mar-12 6:01 
QuestionUsing only description Pin
eyale20-Jan-12 2:34
eyale20-Jan-12 2:34 
SuggestionAvoid Potential Code-Blocking-Error Like This! Pin
pointeman110-Nov-11 6:15
pointeman110-Nov-11 6:15 
SuggestionMeta_Robots? Pin
pointeman110-Nov-11 6:11
pointeman110-Nov-11 6:11 
Questionrevisit-after meta tag Pin
plynn105-Jul-11 11:29
professionalplynn105-Jul-11 11:29 
AnswerRe: revisit-after meta tag Pin
2PointOh28-Jul-11 17:07
2PointOh28-Jul-11 17:07 
GeneralMy vote of 5 Pin
Ricky OLeary26-Jan-11 22:55
Ricky OLeary26-Jan-11 22:55 
GeneralDynamic Keywords Pin
Member 404524230-Jan-10 18:23
Member 404524230-Jan-10 18:23 
GeneralHeader does not exixt in current context.. Pin
Pankil_Plus27-Jun-09 7:50
Pankil_Plus27-Jun-09 7:50 
GeneralRegex does not exist in the current context solved Pin
Ron Curington25-Jun-09 7:29
Ron Curington25-Jun-09 7:29 
General“Regex” does not exist in the current context Pin
Ron Curington25-Jun-09 6:10
Ron Curington25-Jun-09 6:10 
GeneralVisual Studio 2008 Alternate Solution PinPopular
Mike70913-Apr-09 16:28
Mike70913-Apr-09 16:28 
GeneralExcellent Pin
krishna24104-Mar-09 19:26
krishna24104-Mar-09 19:26 
QuestionQuestion about letters in foreign language. Pin
sshenriksen2-Feb-09 8:17
sshenriksen2-Feb-09 8:17 
GeneralLink to your Article Pin
IrishChieftain20051-Feb-09 5:26
IrishChieftain20051-Feb-09 5:26 
GeneralRe: Link to your Article Pin
Jim Azar1-Feb-09 6:44
Jim Azar1-Feb-09 6:44 
QuestionError meassage - 'Meta_Description' is not a valid attribute of element 'Page' [modified] Pin
Erandav28-Dec-08 0:35
Erandav28-Dec-08 0:35 
AnswerRe: Error meassage - 'Meta_Description' is not a valid attribute of element 'Page' Pin
Jim Azar20-Jan-09 4:23
Jim Azar20-Jan-09 4:23 
GeneralLocalization of These Page Directives Pin
JohnGalt1710-Nov-08 5:46
JohnGalt1710-Nov-08 5:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.