OdeToCode IC Logo

Base Classes and Extending the @ Page Directive

Tuesday, July 4, 2006

Q: I'm having problems setting meta tags in my @ Page directive like in your article. My graphics designers don't understand code, but they can deal with page directives. It would be great to have this approach working. Do you have an example I can download?

A: Download the example web project.

The project contains four web forms, one class file, and one master page. The class file defines a base class for all web forms, and looks like the following.

using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;

public class BasePage : Page
protected override void OnInit(EventArgs e)

if (!String.IsNullOrEmpty(MetaKeywords) && Header != null)
HtmlMeta metaTag = new HtmlMeta();
            metaTag.Name =
            metaTag.Content = MetaKeywords;

private string _metaKeywords;
public string MetaKeywords
get { return _metaKeywords; }
set { _metaKeywords = value; }

The article was demonstrating how to use a base class from a web form with inline code. We need a slightly different approach for web forms using code-beside.

This project has four combinations: 

  • web form with inline code and no master page
  • web form with inline code and a master page
  • web form with code-beside and no master page
  • web form with code-beside and a master page.

To set the MetaKeywords property from the @ Page directive with code-beside, you'll need the following:

<%@ Page Language="C#" CodeFile="CodeBeside.aspx.cs"
         CodeFileBaseClass="BasePage" Inherits="CodeBeside"
         MetaKeywords="fluffy wuffy duffy muffy" %>

Notice the use of the CodeFileBaseClass attribute, which is needed for ASP.NET to pick up the Metakeywords property at the time it generates code. The other required step is to make sure the class in the code-beside file derives from the base class we defined.

using System;

public partial class CodeBeside : BasePage

You'll still have red squiggly lines in the @ Page directive. Visual Studio is overly zealous about validating the @ Page directive, and won't like the Metakeywords attribute. This is just a validation error and doesn't prevent the web form from compiling and executing. ASP.NET will generate the right code the words inside the MetaKeywords attribute will render into the HTML output.

This approach isn't limited to just meta tags, we could give the base class other public properties that we can set in the @ Page directive and use at runtime.

Hope that helps...