Using ASP.NET Master Pages
Master Pages and Content Pages
Nested Master Pages
Master Pagesand Content Pages
Assume we have a classical web site like this:
The Master Page – Sections
The header is shared between all pages:
The Master Page – Sections (2)
Navigation
The navigation is shared between all pages:
The Master Page – Sections (3)
Footer
The footer is also shared between all pages:
The content is different for all pages:
Why Use Masterand Content Pages?
Master pages provide reusable UI templates
The structure of the site is repeatedover most of its pages
ASP.NET master pages
allow to share the common HTML between few pages
Common Look & Feel
To avoid the repeating (and copying) of HTML code and the logic behind it
Master pages in ASP.NET Web Forms start with the @Master
directive
Mostly the same attributes as the @Page
directive
Master pages can contain:
Markup for the page (<html>
, <body>
, …
)
Standard contents (HTML, ASP.NET controls)
<asp:ContentPlaceHolder>
controls which can be replaced in the content pages
Content pages
derive the entire content and logic from their master page
Use the @Page
directive with MasterPageFile
attribute pointing to the master page
Replace a <asp:ContentPlaceHolder>
from the master page by using the <asp:Content>
control
Set theContentPlaceHolderID
property
Points to the ContentPlaceHolder
from the Master page which content we want to replace
Master and Content Pages – Mechanics
Master and Content Pages – Advanced
We can change the Master page at runtime in the code-behind
Page. MasterPageFile = " ~/SiteLayout.master" ;
We can also select the Master page according to the browser type
<% @ Page Language= " C#"
ie:MasterPageFile= " ~/IESiteLayout.master"
mozilla:MasterPageFile= " ~/FFSiteLayout.master" %>
Master pages
can be nested, with one master page referencing another as its master
Nested master pages
allow creating componentized master pages
A child master page has the file name extension .master
, as any master page
< ; % @ Master Language="C#" %> ; // Parent Master Page
< ; asp:ContentPlaceHolder ID="MainContent" runat="server"/> ;
< ; %@ Master Language="C#" MasterPageFile="~/Parent.master"%> ;
< ; asp:Content ID="Menu" ContentPlaceholderID="MainContent"
runat="server"> ;
< ; asp:ContentPlaceHolder ID="LeftMenu" runat="server" /> ;
< ; asp:ContentPlaceHolder ID="TopMenu" runat="server" /> ;
< ; /asp:Content> ; // Child Master Page
Free Trainings @ Telerik Academy
"Web Design with HTML 5, CSS 3 and JavaScript" course @ Telerik Academy