ASP.NET Web Forms - Master Pages


Master pages provide a template for other pages of your website.


Master Pages

Master pages allow you to create a consistent look and behavior for all pages (or page groups) in your web application.

Master pages provide a template for other pages, with shared layout and functionality. Master pages define placeholders for content that can be overridden by content pages. The output is a combination of the master page and the content page.

Content pages contain the content you want to display.

When a user requests a content page, ASP.NET merges the pages to produce output that combines the master page layout with the content page content.


Master Page Example

<%@ Master %>

<html>
<body>
<h1>Standard Header From Masterpage</h1>
<asp:ContentPlaceHolder id="CPH1" runat="server">
</asp:ContentPlaceHolder>
</body>
</html>

The master page above is an ordinary HTML template page designed for other pages.

@ MasterThe directive defines it as a master page.

The master page contains placeholder tags for individual content.<asp:ContentPlaceHolder>。

id="CPH1"The attribute identifies the placeholder, allowing multiple placeholders in the same master page.

This master page is saved as"master1.master"。

lampNote: Master pages can also contain code, allowing dynamic content.


Content Page Example

<%@ Page MasterPageFile="master1.master" %>

<asp:Content ContentPlaceHolderId="CPH1" runat="server">
<h2>Individual Content</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</asp:Content>

The content page above is one of the individual content pages in the site.

@ PageThe directive defines it as a standard content page.

The content page contains a content tag<asp:Content>, which references the master page (ContentPlaceHolderId="CPH1").

This content page is saved as"mypage1.aspx"。

When a user requests the page, ASP.NET merges the master page with the content page.

Click here to display mypage1.aspx

lampNote: Content text must be inside the <asp:Content> tag. Content text outside the tag is not allowed.


Content Page with Controls

<%@ Page MasterPageFile="master1.master" %>

<asp:Content ContentPlaceHolderId="CPH1" runat="server">
<h2>EXAMPLE</h2>
<form runat="server">
<asp:TextBox id="textbox1" runat="server" />
<asp:Button id="button1" runat="server" text="Button" />
</form>
</asp:Content>

The content page above demonstrates how to insert .NET controls into a content page, just as you would insert them into an ordinary page.

Click here to display mypage2.aspx


Other Extensions