Making Meta Tags with BasePage
With the introduction ASP.Net 2.0 we can set the Meta
tag from the codebehind file using HtmlMeta class. Instead of repeating the code
that adds the Meta tag on every page we can move this part to BasePage class. A
very good approach will be a exposing a public property in BasePage and setting
the Meta tag from the @Page directive.
Our BasePage will be,
public class BasePage : System.Web.UI.Page
{
private string _metakeywords;
private string _metadescription;
public string MetaKeywords
{
get
{
return _metakeywords;
}
set
{
_metakeywords = value;
}
}
public string MetaDescription
{
get
{
return _metadescription;
}
set
{
_metadescription = value;
}
}
protected override void OnLoad(EventArgs e)
{
if (!String.IsNullOrEmpty(MetaKeywords))
{
HtmlMeta tag = new HtmlMeta();
tag.Name = "keywords";
tag.Content = MetaKeywords;
Header.Controls.Add(tag);
}
if (!String.IsNullOrEmpty(MetaDescription))
{
HtmlMeta tag = new HtmlMeta();
tag.Name = "description";
tag.Content = MetaDescription;
Header.Controls.Add(tag);
}
base.OnLoad(e);
}
}
To make this work we need to include
CodeFileBaseClass="BasePage" attribute in @Page directive in the ASPX. This is
done because in visual studio the codebehind file is referenced through CodeFile
attribute which has the path of the code and this attribute is used to specify
the actual class name. Now we can specify the Meta keywords and descriptions in
@Page directive like,
<%@ Page Language="C#" AutoEventWireup="true"
CodeFileBaseClass="BasePage" CodeFile="Default.aspx.cs"
MetaKeywords="ASP.Net,CSharp" MetaDescription="BasePage implementation in
ASP.Net" Inherits="_Default" %>
This will add Meta tags to every page when it is
rendered. Besides this you can also declare some constants that you require on
every page of your projects.
|