Master Pages Work in ASP.Net C#

What are Master Pages ?

Master pages let you make a consistent layout for your application, you can make one master page that holds the layout/look & feel and common functionality of your whole application and upon this master page, you can build all the other pages, we call these pages Content Pages. So simply you can build your master page and then build content pages, and while creating the content pages you bind them to the master page you have created before, those two pages are merged at runtime to give you the rendered page.



Master Pages and ContentPlaceHolders

The master page has the extension .master and it's actually an aspx page but with the directive <%@ Master Language="C#"%>, instead of the standard page directive, almost the attributes of the Master directive are the same as that of the page, you can add any kind of controls the same as you design aspx pages, and it's advisable to use the menu control at your master page ( menu is one of the most nice added controls to ASP.NET 2.0). Every MasterPage should include at least one ContentPlaceHolder, this control is a placeholder for the content that will be merged at runtime, noting that the content page is just an aspx standard page but you should supply the attribute MasterPageFile to the page directive to bind the content page to the master page, for example:

<%@ Page Language="C#" MasterPageFile="~/MasterPages/Layout.master"%>

Again, you can design your content page just like any other aspx page adding any static text and server controls.



Content Server Control

Inside the content pages you will find one Content server control added by default, actually when you add controls you add them to the content server control. For example,

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">

The attribute ContentPlaceHolderID is very important as it decides what content will be bound to which ContentPlaceHolder on the master page, this is a very nice way to decide the location of where the contents will be displayed; so this way you can have multiple content on one content page and also multiple ContentPlaceHolders on the master page.

Note: The content pages don't include the common tags as <Body>, <Head>,etc. Remember that, that was the same with user controls, as after merging, there should be only one Body and Head tags.

Programmable Master Pages

Master Pages are programmable. You can make one property to the master page and it will be visible to all the content pages, for example you can get one string like last build or last update from web.config file and provide it as a public property to all the content pages.

Maintainable Master Pages

The best thing about master pages is maintainability as you can now update one master page and this will update all your application pages that refer this master page.
Tags: , ,
Hot on Web:


About author