Dynamically changing META Tags with MasterPages (C#)

How to dynamically change meta tags when using MasterPage in ASP.NET and C#
If you have lots of dynamic pages instead of static, you could be losing out on how your pages are indexed. For example, if you use lots of querystrings, the chances are that all pages (or instances of that page) have the same meta tags (title, description, keywords). To overcome this, we can set up our site so that we can set these meta tags dynamically (upon certain actions). If using a MasterPage, this can get a little trickier, but can still be done. This tutorial shows how.
Firstly, on our MasterPage, we give our meta tags and the page title an ID, and runat attribute:


<title id="PageTitle" runat="server">This is the Default Page Title...</title>
<meta name="Keywords" id="PageKeywords" content="default, page, keywords" runat="server" />
<meta name="Description" id="PageDescription" content="This is the Default page desctription, which should be changed when the page is loaded." runat="server" />



public string MetaTitle
{
get
{
return PageTitle.Text;
}
set
{
PageTitle.Text = value;
}
}
public string MetaKeywords
{
get
{
return PageKeywords.Content;
}
set
{
PageKeywords.Content = value;
}
}
public string MetaDescription
{
get
{
return PageDescription.Content;
}
set
{
PageDescription.Content = value;
}
}


The Default.aspx (content page) looks like the following:



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MasterPage myMaster = (MasterPage)this.Master;
myMaster.MetaTitle = "This is the new Page Title, which is set upon Page_Load";
myMaster.MetaDescription = "This is the new Page Description, which is set upon Page_Load";
myMaster.MetaKeywords = "new, page, keywords, set, upon, page, load";
}
}


Download Source Files

Comments