Design Complex Layout with Master Pages

Master pages are a very powerful feature to provide a consistent look and feel for your site. They also help you focus on the content of each individual page, rather than re-implementing for example the navigation of your page each time.

However, sometimes you need to access the master page from one of your content pages (the other way around makes less sense). A cool thing to do is to create strongly-typed master pages. This is achieved by only a single directive, called MasterType. It looks like this:

<% @MasterType virtualPath=”~/MasterPage.master” %>

And you are strongly typed. Let’s assume you have a label called TitleTextLabel on your master page. You can then define its text as a public property in your master.cs code-behind file:

public string TitleText
{
get { return TitleTextLabel.Text; }
set { TitleTextLabel.Text = value; }
}

With the power of strongly-typed master pages, you can set the text of TitleTextLabel from the content page with just the following line of code:

Master.TitleText = “Hello World!”;

Instead of this:

Label TitleLabel = Master.FindControl(“TitleTextLabel”) as Label;
TitleLabel.Text = “Hello World!”;

Decreased chance of an error, IntelliSense support. Two major benefits of using strongly-typed master pages.

You can nest master pages into each other. For example, you can have a main master page, which defines what every site have in common (a global banner for your application, date and time information, etc.). Then you can nest a second level of master pages for each role that will use your application, so they will be presented different menus, for example. The important thing is that every master page and content page must have the same number of ContentPlaceHolder controls and Content controls.

Last: how to assign a master page programmatically. Answer: by setting the Page.MasterPageFile string property to the path of the target master page, in the Page_PreInit event handler.

Further Readings

Strongly Typed Master Pages

NestedASP.NET Master Pages

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s