CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

Adding Custom Property to Page Directive in ASP.Net 2.0
Submitted By Satheesh Babu B
On 11/10/2008 6:50:14 AM
Tags: ASP.Net,CodeDigest  

Adding Custom Property to Page Directive in ASP.Net 2.0

 

We can add a new custom attribute/property to the @Page directive by declaring basepage class and inheriting it with System.Web.UI.Page class. This basepage class should in turn be inherited by the codebehind class. The definition for the new property can be defined here. We need to declare a public property in the basepage class and this public property can be accessed in the @Page directive provided the attribute CodeFileBaseClass="BasePage" is set. 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.

 

Our BasePage class 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 understand better, I have declared 2 string property that takes keywords and description to construct meta tags.

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.

 

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..