How To: Use Meta Tags With ASP.NET Master Pages

Written by James on Wednesday, 21 of March , 2007 at 12:18 pm

There are many articles on adding meta tags to ASP.NET pages. Most involve adding meta tags programmatically, either directly in the page or by having all pages inherit from a base class. There is a better, simpler way.

Ready? Here’s the secret: Use a ContentPlaceHolder. That’s it.

Try it for yourself. Here’s a code example:

  <!-- Web.Master -->

  <%@ Master Language="C#" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml" >
  <head id="Head1" runat="server">
    <title>Master Page</title>

    <asp:ContentPlaceHolder runat="server" id="MetatagsContentPlaceholder">
      <meta name="description"
            content="This is the default description." />
      <meta name="keywords"
            content="keyword, keywords, key phrases" />
    </asp:ContentPlaceHolder>
  </head>

  <body>
    <asp:ContentPlaceHolder runat="server" ID="MainContentPlaceholder">
      default content
    </asp:ContentPlaceHolder>
  </body>
    
  <!--ExamplePage.aspx-->
  <%@ Page Language="C#" MasterPageFile="~/Web.master" Title="Example Page" %>
  <asp:Content ID="Content1" ContentPlaceHolderID="MetatagsContentPlaceholder" Runat="Server">

    <meta name="description"
          content="Page-specific Description" />
    <meta name="keywords"
          content="keywords, for, this, page" />
  </asp:Content>

  <asp:Content ID="Content2" ContentPlaceHolderID="MainContentPlaceholder" Runat="Server">
    You've got meta tags!
  </asp:Content>
    

I think that the reason for the less straight-forward solutions is Visual Studio. When attempting the above in Visual Studio, the following error is reported:

Error 1 Unrecognized tag prefix or device filter 'asp'.

This led me, at first, to think that the solution won’t work. Of course, running the example works just fine and produces the following HTML code:

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml" >
  <head id="ctl00_Head1"><title>
	  Example Page

  </title>
    <meta name="description"
          content="Page-specific Description" />
    <meta name="keywords"
          content="keywords, for, this, page" /></head>

  <body>
    You've got meta tags!
  </body>
    

Related Articles (offsite)

Leave a comment

Category: ASP.NET, SEO

Copyright © 2007 Art of Progress LLC