All of us have struggled over the years to get a consistent look and feel for our web pages. There have been many ways, but now, with ASP.Net 2.0, Master Pages have created a very simple way for this to happen.
To begin with, there’s a new page extension (.Master). So, the first thing to do is to create a new Master page, with the .Master extension, and lay it out any way you’d like. At the top of that page, there’s a Master Directive, much like the Page Directive (and others) you’re already familiar with:
<%@ Master Language="VB" %>
The basic concept is, that you will then create Content pages, which in the Page Directive, will refer to the master page:
<%@ Page Language="VB" MasterPageFile="Main.master" Title="My Content Page" %>
Within each master page, you can have one or more ContentPlaceHolders (a new ASP.Net control):
<asp:contentplaceholder id="cph1" runat="server"> </asp:contentplaceholder>
Then, in the Content Pages, there are new Content controls, which refer back to the ContentPlaceHolder’s ID in the Master Page:
<asp:Content ID="first" ContentPlaceHolderID="cph1" Runat="Server"> Here's where you put the actual content </asp:Content>
The Content Pages use the normal ‘.aspx‘ extension.
One of the really cool features, is that, you can, from the Content pages, refer to any control on/in the Master Page, and change the properties of it. Let’s say you have an ASP.Net Image Control in the top left corner of the Master Page, and you want to change it in your Content page. Just create your image control, using whatever properties you’d like to assign:
<asp:Image id="imMain" Runat="server" />
Then, inside the Page_Load event of your Content page, your code would look something like this:
Dim Img As Image = Master.FindControl("ImMain")
Img.ImageUrl="page2.gif"
You can do this with any DotNet control you put on the Master Page. Let’s say you also have a label control at the bottom of your Master page, for the footer, called ‘lblFooter’. You want it to always say the same on every page, at least. But then, on one or more of your Content pages, you need to add something. So – in the Content Page’s Page_Load event:
Dim lbl as Label=Master.findControl("lblFooter")
lbl.Text=lbl.Text & "
Special Content - Copyright by the Author - Harold Magnolia"
This will keep the same footer that you have on every other page, and also add the extra text (on a second line) above.
To see these basic concepts in action Click Here.
Code for the Master Page:
Continues…