Thursday, February 18, 2010

Setting Page.Title dynamically in C#.net

Recently I have been creating pages with titles in the format: 'Site Name | Page Name'.

Doing so is a relatively painless process, simply place a Key and Value pair for your site name in web.config appSettings as follows:
<appSettings>
<add key="site_name" value="My Website"/>
</appSettings>

Then set the site name to the format required (otherwise it will default to the Title attribute as is in your aspx page directive) by placing the following code in Page_Load of your MasterPage:
protected void Page_Load(object sender, EventArgs e)
{
string site_name = ConfigurationManager.AppSettings["site_name"];

if (!Page.Title.Contains(site_name))
Page.Title = site_name + " | " + Page.Title;
}


However, I came across a situation where I was using a single page (product.aspx) to display any one of the products in my database and so I wanted to set the PageTitle dynamically to include the product name. To do so I added the following lines to Page_Load !IsPostBack on my inner page to set the Page.Title and save it in a ViewState to avoid it reverting to the default on postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string site_name = ConfigurationManager.AppSettings["site_name"];

string product_name = Request.QueryString.ToString(); //Or taken from my database
Page.Title = site_name + " | " + product_name;
ViewState["PageTitle"] = Page.Title;
}
}

And replace the code on your MasterPage to check for the ViewState as follows:
protected void Page_Load(object sender, EventArgs e)
{
string site_name = ConfigurationManager.AppSettings["site_name"];

if (ViewState["PageTitle"] != null)
Page.Title = ViewState["PageTitle"].ToString();
else if (!Page.Title.Contains(site_name))
Page.Title = site_name + " | " + Page.Title;
}

No comments: