Sunday, July 27, 2008

Master Pages - ASP.NET 2.0

Master Pages - The Master Pages feature provides the ability to define common structure and interface elements for your site, such as a page header, footer, or navigation bar, in a common location called a "master page", to be shared by many pages in your site. This improves the maintainability of your site and avoids unnecessary duplication of code for shared site structure or behavior.

Master and Content Pages
Defining a Master Page is just like defining a normal page. Master Pages can contain markup, controls, or code, or any combination of these elements. However, a Master Page can contain a special type of control, called a ContentPlaceHolder control. A ContentPlaceHolder defines a region of the master page rendering that can be substituted with content from a page associated to the master. A ContentPlaceHolder can also contain default content, just in case the derive page does not need to override this content. The syntax of a ContentPlaceHolder control is given below:
<%-- ContentPlaceHolder control --%>

<%-- ContentPlaceHolder with default content --%>

Welcome to my florist website!



To differentiate a Master Page from a normal page, a Master Page is saved under the .master file extension. A page can derive from a Master Page by defining a MasterPageFile attribute on its Page directive, as demonstrated below. A page that is associated to a Master Page is called a Content Page.
<%@ Page MasterPageFile="Site.master" %>

Content Page can declare Content controls that specifically override content placeholder sections in the Master Page. A Content control is associated to a particular ContentPlaceHolder control through its ContentPlaceHolderID property. A Content Page may only contain markup and controls inside Content controls; it cannot have any top-level content of its own. It can, however, have directives or server-side code.
<%@ Page MasterPageFile="Site.master" %>

With sunshine, water, and careful tending, roses will bloom several times in a season.





Accessing a Master Page from CodeIn addition to overriding content, it is possible for a Content Page to programmatically access its Master Page. A Content Page creates a strongly-typed reference to the Master Page using the <%@ MasterType %> directive, specifying the virtual path to the master page:
<%@ MasterType VirtualPath="Site.master" %>

The Content Page can then reference the Master Page using the Master property of the Page class:

Master.FooterText = "This is a custom footer"Dim ad As AdRotator = Master.FindControl("MyAdRotator")

No comments: