Sunday, August 28, 2011

Dynamic Metatag In asp.net c# , Dynamic metatag in master Page

In Master Page :

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<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" /> 


 In Master Page .cs file :

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 MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
   
    }

    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;
        }
    }
}
 

Default.aspx.cs Page :
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 = "Hitendra";
        myMaster.MetaKeywords = "new, page, keywords, set, upon, page, load";
    }
}