Advanced Master Pages
One issue with master pages is how their model assumes you either want to copy something exactly across every page or vary it on each and every page.
This distinction works well for many pages, but it runs into trouble if you want to allow a more nuanced interaction between the master page and content pages.
For example, you might want the master page to give a choice of three display modes. The content page would then choose the correct display mode, which would change the apperance of the master page. However, the content page shouldn't have complete freedom to change the master page indiscriminately. Instead, anything other than these three prests should be disallowed.
To enable step in allowing interaction between your content page and master page is to add public properties or methods to your master page class. The content page can then set these properties or call these methods accordingly. For example, maybe you want to make the banner text customizable but you don't want to let the content page insert any type of content there. Instead, you want to restrict it to a single descriptive string. To accomplish this, you can add a server side label controll to the header and provice access to that control through a BannerText property in the master page class:
1: public string BannerText
2: {
3: get { return lblTitleContent.Text; }
4: set { lblTitleContent.Text = value; }
5: }
The content page can now change the text. The only caveat is that the Master property returns an object that's typed as the generic MasterPage class. You need to cast it to your specific master page class to get access to any custom member's you've added.
1: protected void Page_Load(object sender, EventArgs e)
2: {
3: SiteTemplate master = (SiteTemplate)Master;
4: master.BannerText = "Here i come from Page 1";
5: }
Another way to get strongly typed access to the master page is to add the MasterType directive to the content page. All you need to do is indicate the virtual path of the corresponding .master file
<%@ MasterType VirtualPath="~/SiteTemplate.master" %>
Noy you can use simpler strongly typed code when you access the master page:
1: protected void Page_Load(object sender, EventArgs e)
2: {
3: Master.BannerText = "Content Page #1";
4: }
You should note one point about these examples: when you navigate from one page to another, all the web-page objects are re-created. This means that even if you move to another content page that uses the same master page, ASP.NET creates a different istance of the master page object. As a result, the Text property of the Label control in the heade ris reset to its default value every time the user navigates to a new page. To change this behavior you need to store the information in another location (whenever you want) and write initialization code in the master page to check for it.
You can also get access to an individual control on a master page through brute force (last post).