Friday, April 13, 2007

Master Pages and Dynamic Page Titles – how to set from web controls inside the page?

Well, we all know how to set dynamic page titles. When using master pages, we can still control the page titles from the actual page itself. How about a need where master always sets the static part of the page title and page prefixes some specific information? And then how about when the page has complex nest of controls, like a wizard and in the wizard a web control, say product control, and based on the product selected to set the prefix as the product name?

To do that, we need to understand the page life cycle of ASP.Net (refer to http://msdn2.microsoft.com/en-us/library/ms178472.aspx for detailed explanation). Getting to the point in need, let’s focus on these three event sequences:

Ø Load (for both Master and the current page)

Ø Control Events (in our case the product web control)

Ø LoadComplete (doesn’t occur in Master, only to the page)

As we see in the above sequence, we can set the Master’s static part in it’s Load event. The control events load up our product information, including the product name. And, finally, the LoadComplete event of the page can read the product name in the control (with a property) and prefix it to the Master’s title.

A simple example:

Master Page:

Create the head section with runat server:

<head id="myHead" runat="server">

In the Page_Load event, we could add the static heading part as:

myHead.Title = "MyBlog.com – C# & Asp.Net";

And then create a public property for the header:

public string myHTMLTitle

{

get { return myHead.Title; }

set { myHead.Title = value; }

}

Product Web Control:

Load the product information and do any other related stuff. Add the ProductName public property:

public string ProductName

{

get { return myProduct.Name; }

}

Product Page:

Finally, in the product page, create Page_LoadComplete event and set the title:

protected void Page_LoadComplete(object sender, EventArgs e)

{

Master.myHTMLTitle = prod.ProductName + " - " + Master.myHTMLTitle;

}

But wait, did you get the 'System.Web.UI.MasterPage' does not contain a definition for 'myHTMLTitle' error? Then you need to set the virtual path to the master page - <%@ MasterType VirtualPath="~/myDir/myMaster.master" %>

Love coding!

No comments: