web sites generally show the section of the site you are in by adjusting the title of the page. For example "nirandas >> blog", "Weblog of Nirandas >> asp.net pages and proper title" etc. There is a common part and a part which changes according to the section your currently browsing. Now developing asp.net sites, you only got a title property to set. The simple thing to do would be to setthe the complete title every time you change the title. Like this.Title = "Nirandas >> Profile of Nirandas"; Surely not elegant enough.

An alternative and more clean solution is to use a common base page for all of your pages and write some code to format the title according to your need. For example you could have a property named Heading in the base page and all of your page set the heading as required. Now the interesting part, your title can be something like this "Weblog of Nirandas >> {0}". And our code in the page's PreRender Event can set the title after formatting the heading using the title. Like

this.Title = string.Format(this.Title,this.Heading);

This way, the page designers will have complete control over the format of the title and it also provides a clean way for coders to set the appropriate title. A tricky thing with this approach is when a page does not set it's Heading property. In this case, the default value of the Heading will be used to fill the place holder making the title useless and strange. Obviously, the developers should always set the proper heading. Or if the page does not require dynamic title, the designers can avoid using the place holder "{0}" in the title.

Example page follows:

MyBasePage.cs

using System;
using System.Web;
using System.Web.UI;

public class MyBasePage : Page
{
private string _Heading = "Default Heading";

public string Heading {
get {return _Heading;}
set {_Heading = value;}
}

protected override void Render(HtmlTextWriter writer)
{
this.Title = string.Format(this.Title, this.Heading);
base.Render(writer);
}
}

Code description

The class derives from the Page class and contains a custom property named "Heading". The pages which will derive from this page should set the Heading property to a relevant value. Then we override
the page's Render method and use the value of the Heading property to format the page's title using string.Format() function. Now the pages which want this functionality,
should derive from this class and set the appropriate value to used in place of the Heading place holder. The designers can set
the title of the page in the aspx page as follows.

<%@ page ... title="info about {0}"%>

Now the programmer will set the Heading as

this.Heading = "India";

When the page renders, the title will be automatically changed to "info about India".

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList