Metadata From Content To Master Page

by Duane 25. January 2009 19:48

The ASP.NET Master page concept is a great idea until you start thinking about search engine optimization. Search engines prefer metadata that is relevant to the page's content. The meta description should be a summary of what's on the content page and the keywords should also be relevant to page content. Setting a title from your content page is easy enough since it's built in. What about the metadata?

There are many ways to dynamically change the master pages metadata that range from using the content page's CodeBehind to fully database driven. Here I will describe a lean and mean way to do it from the content pages CodeBehind and provide code samples in VB.NET and C#. Please note that this is best used on a smaller site.

This example uses a class called HeaderFunctions and adding the Page_PreRender code block to your content page's CodeBehind.

VB.NET

Create the HeaderFunctions Class

Imports Microsoft.VisualBasic

Public Class HeaderFunctions

    Public Shared Sub AddMetaTags(ByRef htmlhead As HtmlHead, _
    ByVal metaname As String, ByVal metacontent As String)
        Dim htmlmeta As New HtmlMeta
        htmlmeta.ID = metaname
        htmlmeta.Attributes.Add("name", metaname)
        htmlmeta.Attributes.Add("content", metacontent)
        htmlhead.Controls.Add(htmlmeta)
        htmlhead.Dispose()
    End Sub

End Class

Add this to your Content page's CodeBehind

    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        HeaderFunctions.AddMetaTags(Page.Header, "keywords", "Your keywords here")
        HeaderFunctions.AddMetaTags(Page.Header, "description", "Your Description here")
    End Sub

C#

Create the HeaderFunctions Class

using Microsoft.VisualBasic;

namespace Shared
{
    public class HeaderFunctions
    {
        public static void AddMetaTags(ref HtmlHead htmlhead, string metaname, string metacontent)
        {
            HtmlMeta htmlmeta = new HtmlMeta();
            htmlmeta.ID = metaname;
            htmlmeta.Attributes.Add("name", metaname);
            htmlmeta.Attributes.Add("content", metacontent);
            htmlhead.Controls.Add(htmlmeta);
            htmlhead.Dispose();
        }

    }
}

Add this to your Content page's CodeBehind.

protected void Page_PreRender(object sender, System.EventArgs e)
{  
     HtmlHead p = Page.Header;
     Shared.HeaderFunctions.AddMetaTags(ref p, "keywords", "Your keywords here");
     Shared.HeaderFunctions.AddMetaTags(ref p, "description", "Your Description here");
}

My next article will be on a data driven metadata application.  Until then happy coding!

Currently rated 5.0 by 5 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading