C# Adding MetaData to Master page from Child page dynamically

As for adding metadata description and keywords to your master page from your child page can be done through many ways. Here from my redirect to HTTPS connection, also gave me the idea that the same concept can be adept for adding meta to page which is inherence from a master page.


The concept is easy, first in the master page Asymmetric Accessor that create a ViewState varible. Then when you call the accessor from the child page to set the value, on the master page OnPreRender() method the meta data will be added to the rendered html page ready to be sent to the client.

Masterpage.master.cs

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

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected override void OnPreRender(EventArgs e)
    {
        if (Description != null)
        {
            HtmlMeta metaD = new HtmlMeta();
            metaD.Name = "description";
            metaD.Content = Description;
            this.Page.Header.Controls.Add(metaD);
        }
        if (Keywords != null)
        {
            HtmlMeta metaK = new HtmlMeta();
            metaK.Name = "description";
            metaK.Content = Keywords;
            this.Page.Header.Controls.Add(metaK);
        }
        base.OnPreRender(e);
    }
    public string Description
    {
        get
        {
            if (ViewState["MetaDescription"] != null)
                return (string)ViewState["MetaDescription"];
            else
                return null;
        }
        set
        {
            ViewState["MetaDescription"] = value;
        }
    }
    public string Keywords
    {
        get
        {
            if (ViewState["MetaKeywords"] != null)
                return (string)ViewState["MetaKeywords"];
            else
                return null;
        }
        set
        {
            ViewState["MetaKeywords"] = value;
        }
    }
}

Add when you want to add metadata to your page con rendering to the client

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        (Master as MasterPage).Keywords = "sarin, mobi";
        (Master as MasterPage).Description = "Sarin Information Technology Expert";
    }
}

Cool nice and short when using, here the html results





/

There are many ways that you can implement this feature, if anyone else has better solutions please post a comment or link to the blog, would be great thanks

  • http://piupuno.freehostguy.com Alek
  • http://www.sarin.mobi Sarin Na Wangkanai
  • kookimebux
  • http://elmasry ahmed
  • Thanh