Click here to Skip to main content
12,549,332 members (46,959 online)
Click here to Skip to main content
Add your own
alternative version


120 bookmarked

Using Meta Tags with Master Pages in ASP.NET

, 24 May 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
Extend the @Page directive so that you can specify meta keywords and meta descriptions on content pages.


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.


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="" >
   Rhinoback Professional Secure Online Backup Services for Small 
   and Medium Business - SMB
<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" />
     <!--<span class="code-comment"> page content --></span>

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:


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


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"
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.


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.


/* ********************************************** 
 * Page directive extender - base page class    *
 *  by Jim Azar -      *
 * **********************************************/

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

/// <span class="code-SummaryComment"><SUMMARY>


'* ********************************************** 
'* Page directive extender - base page class    *
'*  by Jim Azar -      *
'* **********************************************/

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
        End If

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

    'Gets or sets the Meta Keywords tag for the page
    Public Property Meta_Keywords() As String
            Return _keywords
        End Get
            ' 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
            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:


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



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" 
  Title="My home page title" 
  Meta_Keywords="page directive, extension, dotnet,"
  Meta_Description="This is the meta description for my home page."          

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" 
    <h3>My home page content<h3>
    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. 

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"
  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.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Jim Azar
Web Developer
United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionNeed a little more help on this please Pin
Rachel828-May-15 9:45
memberRachel828-May-15 9:45 
Questionusing meta tag with master page Pin
sanjoysharan20-Mar-13 18:30
membersanjoysharan20-Mar-13 18:30 
QuestionNice Article Pin
widnson8-Jul-12 5:02
memberwidnson8-Jul-12 5:02 
QuestionApp_Code folder not working online. Pin
Pagem197222-May-12 4:20
memberPagem197222-May-12 4:20 
QuestionMasterPage Keywords Pin
corprosystems26-Mar-12 6:01
membercorprosystems26-Mar-12 6:01 
QuestionUsing only description Pin
eyale20-Jan-12 2:34
membereyale20-Jan-12 2:34 
SuggestionAvoid Potential Code-Blocking-Error Like This! Pin
pointeman110-Nov-11 6:15
memberpointeman110-Nov-11 6:15 
SuggestionMeta_Robots? Pin
pointeman110-Nov-11 6:11
memberpointeman110-Nov-11 6:11 
Questionrevisit-after meta tag Pin
plynn105-Jul-11 11:29
memberplynn105-Jul-11 11:29 
AnswerRe: revisit-after meta tag Pin
2PointOh28-Jul-11 17:07
member2PointOh28-Jul-11 17:07 
GeneralMy vote of 5 Pin
Ricky OLeary26-Jan-11 22:55
memberRicky OLeary26-Jan-11 22:55 
GeneralDynamic Keywords Pin
Member 404524230-Jan-10 18:23
memberMember 404524230-Jan-10 18:23 
GeneralHeader does not exixt in current context.. Pin
Pankil_cool27-Jun-09 7:50
memberPankil_cool27-Jun-09 7:50 
GeneralRegex does not exist in the current context solved Pin
Ron Curington25-Jun-09 7:29
memberRon Curington25-Jun-09 7:29 
General“Regex” does not exist in the current context Pin
Ron Curington25-Jun-09 6:10
memberRon Curington25-Jun-09 6:10 
NewsSource code available online Pin
Gilad Khen30-May-09 16:48
memberGilad Khen30-May-09 16:48 
GeneralVisual Studio 2008 Alternate Solution Pin
Mike555555555555555555513-Apr-09 16:28
memberMike555555555555555555513-Apr-09 16:28 
GeneralExcellent Pin
krishna24104-Mar-09 19:26
memberkrishna24104-Mar-09 19:26 
QuestionQuestion about letters in foreign language. Pin
sshenriksen2-Feb-09 8:17
membersshenriksen2-Feb-09 8:17 
GeneralLink to your Article Pin
IrishChieftain20051-Feb-09 5:26
memberIrishChieftain20051-Feb-09 5:26 
GeneralRe: Link to your Article Pin
Jim Azar1-Feb-09 6:44
memberJim Azar1-Feb-09 6:44 
QuestionError meassage - 'Meta_Description' is not a valid attribute of element 'Page' [modified] Pin
Erandav28-Dec-08 0:35
memberErandav28-Dec-08 0:35 
AnswerRe: Error meassage - 'Meta_Description' is not a valid attribute of element 'Page' Pin
Jim Azar20-Jan-09 4:23
memberJim Azar20-Jan-09 4:23 
GeneralLocalization of These Page Directives Pin
JohnGalt1710-Nov-08 5:46
memberJohnGalt1710-Nov-08 5:46 
GeneralNice article, well written! Pin
Adam Tibi18-Sep-08 5:31
memberAdam Tibi18-Sep-08 5:31 
GeneralExcellent ! Pin
Snekemoi18-Jul-08 11:05
memberSnekemoi18-Jul-08 11:05 
GeneralCompiler error - make sure this code file matches the 'inherits' attribute and extends the correct base class Pin
redwoodbev21-Jun-08 22:19
memberredwoodbev21-Jun-08 22:19 
QuestionSet Description via Codebehind? Pin
ajhopen27-May-08 4:15
memberajhopen27-May-08 4:15 
AnswerRe: Set Description via Codebehind? Pin
ajhopen1-Jun-08 13:30
memberajhopen1-Jun-08 13:30 
GeneralThis solved two problems! Pin
DViolette5-May-08 8:21
memberDViolette5-May-08 8:21 
Generalgetting title, keywords, description using code-behind. Pin
kebuidoidenbac28-Apr-08 19:25
memberkebuidoidenbac28-Apr-08 19:25 
GeneralRe: getting title, keywords, description using code-behind. Pin
Jim Azar29-Apr-08 2:12
memberJim Azar29-Apr-08 2:12 
QuestionPlacement of code? Pin
PhotoJoe19-Apr-08 8:02
memberPhotoJoe19-Apr-08 8:02 
GeneralRe: Placement of code? Pin
Jim Azar21-Apr-08 4:43
memberJim Azar21-Apr-08 4:43 
QuestionNull Object Reference Error Pin
blueisland152028-Nov-07 2:30
memberblueisland152028-Nov-07 2:30 
AnswerRe: Null Object Reference Error Pin
jroger0429-Nov-07 10:56
memberjroger0429-Nov-07 10:56 
AnswerRe: Null Object Reference Error Pin
blueisland152014-Dec-07 10:57
memberblueisland152014-Dec-07 10:57 
GeneralAlternative solution Pin
Darov26-Oct-07 0:32
memberDarov26-Oct-07 0:32 
GeneralRe: Alternative solution Pin
Darov26-Oct-07 0:34
memberDarov26-Oct-07 0:34 
GeneralRe: Alternative solution Pin
jroger0426-Oct-07 1:57
memberjroger0426-Oct-07 1:57 
GeneralRe: Alternative solution Pin
Darov26-Oct-07 2:19
memberDarov26-Oct-07 2:19 
GeneralRe: Alternative solution Pin
Anton Buttigieg20-Nov-07 1:15
memberAnton Buttigieg20-Nov-07 1:15 
GeneralRe: Alternative solution Pin
Member 453014115-May-08 10:59
memberMember 453014115-May-08 10:59 
GeneralRe: Alternative solution Pin
Spector 64-Nov-08 22:45
memberSpector 64-Nov-08 22:45 
Generalerror with the code Pin
Joewb25-Sep-07 16:30
memberJoewb25-Sep-07 16:30 
GeneralRe: error with the code Pin
Joewb26-Sep-07 8:47
memberJoewb26-Sep-07 8:47 
QuestionThe Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;). Pin
epeart18-Sep-07 7:31
memberepeart18-Sep-07 7:31 
AnswerRe: The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;). Pin
jroger0426-Oct-07 1:53
memberjroger0426-Oct-07 1:53 
GeneralRe: The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;). Pin
jroger0429-Nov-07 11:09
memberjroger0429-Nov-07 11:09 
GeneralRe: The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;). Pin
mr zayar19-Mar-08 23:36
membermr zayar19-Mar-08 23:36 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161021.1 | Last Updated 24 May 2007
Article Copyright 2007 by Jim Azar
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid