Master Pages in ASP.NET

Master Pages

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

A master page provides a template for other pages, with shared layout and functionality. The master page defines placeholders for the content, which can be overridden by content pages. The output result is a combination of the master page and the content page.

The content pages contain the content you want to display.

When users request the content page, ASP.NET merges the pages to produce output that combines the layout of the master page with the content of the content page.

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 a normal HTML page designed as a template for other pages.

The @ Master directive defines it as a master page.

The master page contains a placeholder tag <asp:ContentPlaceHolder> for individual content.

The id=”CPH1″ attribute identifies the placeholder, allowing many placeholders in the same master page.

This master page was saved with the name “master1.master”.

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 of the web.

The @ Page directive defines it as a standard content page.

The content page contains a content tag <asp:Content> with a reference to the master page (ContentPlaceHolderId=”CPH1″).

This content page was saved with the name “mypage1.aspx”.

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

Content Page With Controls

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

<asp:Content ContentPlaceHolderId=”CPH1″ runat=”server”>
  <h2>W3Schools</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 .NET controls can be inserted into the content page just like an into an ordinary page.

Author: Vikas Kansal

Hi.. I am Vikas Kansal. I am a "Computer Faulty" and a "Software & Web developer". I am an active member of A Social and Educational Organization NIRMAN.

Leave a Reply

Your email address will not be published. Required fields are marked *