Thursday, May 06, 2010

aspx MasterPage.Master Meta Notes

The master page can’t set the title for each content page in an application. Only the content pages know what thier title will be. Fortunately, ASP.NET provides a public property on the Page class, and we can set a content page’s title declaratively in the @ Page directive.

example:
< % @ Page Language="VB" MasterPageFile="~/Master1.master"
AutoEventWireup="true" Title="Home"
% >

A Page Directive Approach

Another approach is possible which provides the same flexibility and convenience of the Title attribute. For example, what if we wanted to set the meta keywords of a page in the @ Page directive?

<%@ Page Language="VB" MasterPageFile="~/Master1.master"
AutoEventWireup="true" Title="Home" Inherits="BasePage"
MetaKeywords="masterpage ASP.NET"
%>

To use the MetaKeywords attribute in every page of an application, we just need to inherit from a common base class that exposes a MetaKeywords property. The base class can also inject the meta tag into the page header.

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

public class BasePage : Page
{
public BasePage()
{
Init += new EventHandler(BasePage_Init);
}

void BasePage_Init(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(MetaKeywords))
{
HtmlMeta metaTag = new HtmlMeta();
metaTag.Name = "Content";
metaTag.Content = MetaKeywords;
Header.Controls.Add(metaTag);
}
}

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

No comments:

Wiredwizrd

Morgan Todd Lewistown, PA

Experienced Information Technology Manager with a strong knowledge of technical guidance, IT best practices, security protocols, team leadership, and analyzing business requirements.
Google