Journey to MCTS 70-515: Lesson 4 – Master Pages
February 7, 2011 Leave a comment
Precedence
If a property is set on the content page to true but the same property is set to false in the master page then the setting on the master page takes priority.
Referencing Properties
To reference any master page properties from content pages do the following,
- Create a public property in the master page code-behind file.
- Add the @MasterType declaration to the ASPX content page.
- Reference the master page property from the content page by using the syntax Master.<Property_Name>.
Actual Scenario: -
Question 1:
Default.aspx uses a master page named Site.master. You add the following code to the Default.aspx code-behind file to read a Site.master public property named Username.
protected void Page_Load(object sender, EventArgs e)
{
string s = Master.Username;
}
You need to ensure that Default.aspx can access the Username property. What should you do?
- Add the following directive to Default.aspx.
<%@ MasterType VirtualPath=”~/Site.master” %>
- Add the following directive to Default.aspx.
<%@ PreviousPageType VirtualPath=”~/Site.master” %> - Set the Strict attribute in the @ Master directive of the Site.master page to true.
- Set the Explicit attribute in the @ Master directive of the Site.master page to true.
Referencing Controls
Apart from properties, controls can also be referenced and updated in the master page from any content page using the Master.FindControl method. You only need to pass this method the name of the control. Master.FindControl returns a Control object that would need to be casted to the correct control type. After this reference is made, you can read or update the object as if it were local to the content page.
The following code (in the Page_Load method of the content page) updates a Label control named lblWebsite in the master page,
Label MyWebsite = (Label)Master.FindControl("lblWebsite");
MyWebsite.Text = "IRTAZAALI.COM";
Dynamically Changing Master Pages
Page_PreInit method is the last opportunity to override the default master page setting. This is because after this event the content page binds with the master page preventing it from being changed.