Master pages introduced with ASP.NET 2.0, enables developers to maintain consistent look and feel across all the pages in a web application. Normally, most of us use frames, where we divide one single page into various sections like header for logo and captions, footer for contact information and load different pages in those sections or directly create the header and footer repeated on each and every web page or create separate web user controls for header and footer and load them on every web page. This comes as a built-in feature for Master pages.
Master pages are most similar to normal aspx pages, except they have a different extension named “.master”. Master page will have a directive <%@ Master %> which indicates that this is a master page. Master page has ContentPlaceHolder controls which act as a place holder for a content area where actually our content pages will inject their content into. Master page can contain one or more content placeholders. Content pages will simply have a reference to the ID of the ContentPlaceHolder on the master page into which it injects its content into.
Example of how to create a master page:
Add a new master page from Visual Studio and name it “exampleMaster.master”
- <%@ Master Language=”C#” %>
- <head><title>Master Page Example</title></head>
- <form runat=server>
- <td colspan=”2”>
- <asp:ContentPlaceHolder ID=”headerContentHolder” runat=”server”>
- <asp:ContentPlaceHolder ID=”leftContentHolder” runat=”server”>
- <asp:ContentPlaceHolder ID=”rightContentHolder” runat=”server”>
- <td colspan=”2”>
- <asp:ContentPlaceHolder ID=”footerContentHolder” runat=”server”>
The above code creates four different sections in the master page for header, footer, left content and right content. After having the master page we need to create content pages using master page as a template. Content pages are simple aspx pages which have reference to master page in its page directive and will contain only <asp:Content> control in which all the code for the corresponding ContentPlaceHolder will be embedded.
Example of Content pages:
- <%@ Page Language=”C#” MasterPageFile=”~/exampleMaster.master” %>
- <asp:Content id=”content1” ContentPlaceHolderID=”headerContentHolder” runat=”server”>
- // Place your content to be displayed in the header of Master page
This content page will be referring its master page through “MasterPageFile=”~/exampleMaster.master” attribute placed in its page directive and content inside it will be placed in the ContentPlaceHolder with the id “headerContentHolder” in the master page.
Similar to this, we can create three more content pages for footer, left menu and right content. Make a note that master pages cannot be directly “Set as startup page” for web applications. Master pages will just act as a template for content pages and we can use only content pages as start up pages.