Setting Page Meta Information at Runtime

I have a MasterPage and some child pages. The content for the child pages comes from a database. I have a form in the Admin section of my site for editing pages. You can set the Page Title, the Meta Description, Keywords, and page Content.

Accessing the title is easy, because the title of the content pages (in the @Page directive) applies to the MasterPage. Getting to the Meta information is a little trickier.

Thanks to Chris Garrett for his tip at http://aspalliance.com/411_Setting_the_ASPNET_Page_Title_and_Meta_Tags.

First, in the content pages, I have to add

<%@ MasterType VirtualPath=”~/MasterPage.master” %>

to the child pages, right under the @Page directive. With this, I can type “Master.” in the codebehind and access all the public properties of the MasterPage.

Second, on the MasterPage, I have to add two Public Properties. One for the Meta Description, and one for the Meta Keywords.

Public MetaDescription As String = “”
Public MetaKeywords As String = “”

Third, in the HTML code for the page, I make the two Meta tags server controls. I always set the Head tag to runat=”server”.

<head runat=”server” id=”Head1″>
<title
/>
<meta id=”Description” runat=”server” content=”description” name=”description”
/>
<meta id=”Keywords” runat=”server” content=”keys” name=”keywords” />

Fourth, on the Page_Load of the MasterPage, I can set the Title and Keywords at runtime.

Description.Attributes(“content”) = “Demo Description”
Keywords.Attributes(“content”) = “Keyword 1, Keyword 2”

I am now pulling the Meta information directly from the database at runtime, and setting Page.Title, Master.Description, and Master.Keywords from the Load event of the Child page.

In the Load event of the MasterPage, I can add some simple logic to give all pages a meta description.

If MetaDescription.Length = 0 Then
    Description.Attributes(“content”) = “My Generic Description. This description appears on all pages where the MetaDescription in the database is empty.”
Else
   
Description.Attributes(“content”) = MetaDescription
End If

If MetaKeywords.Length = 0 Then
   
Keywords.Attributes(“content”) = “Generic, Default, Consistent, Normal”
Else
   
Description.Attributes(“content”) = MetaKeywords
End If

This is how I use MasterPages, and it works pretty well!

Zachary Lyons