Dynamically Set Title and Meta Tags with MasterPages
Wednesday, June 14th, 2006I use MasterPages in all of my ASP.NET websites. I can’t even imagine having a site that doesn’t use them. If you have pages with dynamic content it is important to be updating your page title and meta tags to correspond to the page content. This is probably most important if you have public-facing websites and care about Search Engine Optimization. Thankfully there are a couple of easy ways to dynamically change your title and meta tags.
To begin, add a 3 properties to your MasterPage class (MasterPage.master.cs) to hold the values for title, meta description, and meta keywords.
public string PageTitle
{
get { return _pageTitle; }
set { _pageTitle = value; }
}private string _metaDescription;
public string MetaDescription
{
get { return _metaDescription; }
set { _metaDescription = value; }
}private string _metaKeywords;
public string MetaKeywords
{
get { return _metaKeywords; }
set { _metaKeywords = value; }
}
Next you will need to edit the head section of your MasterPage.master file to use the properties we just added.
<meta name=”keywords” content=’<%# MetaKeywords %>’ />
</head>
Finally you set the properties of the PageTitle, MetaDescription, and MetaKeywords on the OnLoad event of your page. Make sure you keep the call to Page.DataBind().
myMaster.MetaKeywords = “keyword 1, keyword 2, keyword 3″;
Page.DataBind();