You are here:   Units 1 to 4 > 3. Master Pages
  |  Login

Layout

Minimize
Master Page
Page specific content is dynamic and gets updated through the use of a ContentPlaceHolder control.  Everything else is static and is defined on the master page.
Page specific content is dynamic and gets updated through the use of a ContentPlaceHolder control. Everything else is static and is defined on the master page.
Master Page Fused
When a new page is loaded, a new content page gets loaded in the content place holder. This basically fuses the static page with the new dyanmic content to form one page
When a new page is loaded, a new content page gets loaded in the content place holder. This basically fuses the static page with the new dyanmic content to form one page

Adding A Master Page


 

Master pages have the extension .master and you can add them to your project the same way that you add any other web form. Simply right click on the your project and select "Add New Item" then select master page:

Master Pages



Most web sites have a typical layout that consists of a header, footer, menu, and a content area. When you click a link the common regions like header, footer, and menu do not change. To create a web page in such a fashion you need a mechanism that will handle the static content and allow the dynamic content to display. Basically you want a single template that can be applied to all pages of your web site. This is where the master page comes to the rescue.

You should know that a master page is not a true .aspx page and cannot be loaded directly into the browser. It only serves as a template that the real web pages (called content pages) are based on.

A basic master page has static content and page specific content. The page specfic content gets changed depending on the link. The content is updated through the use of a ContentPlaceHolder control that is used to change out content pages.
Adding a Master Page
In Visual Studio right click on the project and select add new item. Select web and  then Master Page
In Visual Studio right click on the project and select add new item. Select web and then Master Page

ContentPlaceholder


 

You use these controls to define where content will be placed inside the web  forms that are created from the master page. The ContentPlaceHolder has one significant property and that is it's ID. You can use this later on to reference the content area

ContentPlaceHoder
You use these templates where you want content placed. You can add these through the toolbox if you need multiple content areas
You use these templates where you want content placed. You can add these through the toolbox if you need multiple content areas
Create a Layout


Once you have created the MasterPage you need to create a layout. Below is an example of a simple 3 frame layout that includes a header, sidebar, and main content area. Notice that the content area contains a ContentPlacholder where content pages will get loaded into.

The image on the left depicts the code and the image on the right shows a designer view. You should also note that an external stylesheet is being used to set the colors and the fonts.
Master Page Layout
Use div and css to create a simple 3 frame layout
Use div and css to create a simple 3 frame layout
Master Page Layout Design View
Design view of the 3 frame layout using div and css
Design view of the 3 frame layout using div and css

Create a Home Page


If you have created a home page you may want to consider creating a new one. The reason for this is a content page is created slightly different. When you want to use a MasterPage you need to add a new item. Instead of adding a web form, you want to add a "Web Form using Master Page" and then select the MasterPage to associate with it.

If you look at the content form you will notice that it  contains only content place holders for you to  html markup and asp.net server controls in it

Web Content Form
Select the Web Content Form and then select the MasterPage to Associate with it
Select the Web Content Form and then select the MasterPage to Associate with it
Web Content Form Source
Notice that the Web Content Form only contains content place holders for you to put your html markup and asp.net server controls in
Notice that the Web Content Form only contains content place holders for you to put your html markup and asp.net server controls in

Add Content To The Web Content Form


All that is left to do is add html markup to your content page. In this example, I have simply added some dummy content to the page for effect. If you look closely it may be familiar to you.

Master Page With Content
A simple layout in the content place holder using HTML and asp.net server controls.
A simple layout in the content place holder using HTML and asp.net server controls.
HTML and ASP.NET controls added
Notice the markup is placed within the content place holders
Notice the markup is placed within the content place holders

Video - Creating and Using a MasterPage


 

The following video walks you through the creation and use of MasterPages

Base Pages



Through inheritance all ASPX pages are derived from a class called System.Web.UI.Page. What this means is that this class is the parent to every page you create. This allows for common behavior amongst all pages. Occasionally though the default behavior may not be enough. So, You could simply add the new behavior to the page yourself. The problem here is that if you have multiple pages that need to have this new behavior you would have to duplicate it in each page.  This is kind of thing is something that we really want to avoid in programming.

The solution then is to create a base page that kind of serves as an intermediary page. The base page would be derived System.Web.UI.Page and here is where you would add your specific behavior. Then all of the pages that need this behavior would simply be derived from your base page.

The following illustrates this:
Base Page
Depicts how a base page can be used as an intermediary page to add custom behaviors
Depicts how a base page can be used as an intermediary page to add custom behaviors
Page Life Cycle


Before looking at how a base page is implemented it is best to get an understanding of the life cycle of an ASP.NET page.

The life of the page begins with the initial request from the browser. There are actually eight events that happen in the life of an ASP.NET page:

Stage

Description

Page request

The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start

In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.

Initialization

During page initialization, controls on the page are available and each control's UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

Load

During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Postback event handling

If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

Rendering

Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page's Response property.

Unload

The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.


Understanding the page life cycle is important for such things as dynamically changing the theme which needs to be done early in the page life cycle. This will also become more important when the subject of state is covered.


Implementing a BasePage


To add a BasePage to your project simply right click on the project and select Add / New Item then select class:
BasePage
Notice the name of the class is BasePage. This is not required but suggested so that it is easily identified.
Notice the name of the class is BasePage. This is not required but suggested so that it is easily identified.
BasePage Code

Once you have added the class you need to write code to make the base page do whatever functionality you choose. Before doing that you need to make sure that the parent of the BasePage is Page. This is pretty simple thing to do and can be accomplished with the following code:

public class BasePage : System.Web.UI.Page

BasePage is the class you added the colon indicates that inheritance is taking place and the System.Web.UI.Page is going to be the class to be inherited from.

The example code below shows how to generate an error if the PageTitle is not changed from Untitled Page.

Notice that the error checking happens in the Page_PreReneder event. This event happens just before the page is rendered to the screen so this seems appropriate. You could however put code in any event that you see fit. For instance, you might want to connect to a database in the Page_Load event.
Code for Base Page
Notice how the inheritance is accomplished through the use of the colon. Also, the checking for Untitled Page happens in the prerender event.
Notice how the inheritance is accomplished through the use of the colon. Also, the checking for "Untitled Page" happens in the prerender event.
Implementing A Base Page


Once you have created a Base Page the final step is to simply implement it. This involves telling your pages to be derived from BasePage and not page.

To do this you must first open up your CodeBehind file. If you are not sure how to do this you simply expand the aspx page in the solution explorer and choose the file with the extension .cs. If you are using VisualBasic this extension will be .vb:

Code Behind
If the .cs file is not there view the page in the designer and double click somewhere within the page. This will force the creation of a CodeBehind
If the .cs file is not there view the page in the designer and double click somewhere within the page. This will force the creation of a CodeBehind
Now you simply need to change the code in the code behind file to reflect that you want the page to be derived from BasePage not Page. So you simply need to change the code after the colon to BasePage.

The example on the left shows the page before changing the inheritance. The example on the right shows the change to make the code derived from BasePage:
No Inheritance
Shows the code before inheritance
Shows the code before inheritance
Running The Page


Now if you run the page using start without debugging you will get the error on the right. If you run it in debug mode you will get the error on the left:
Running in Debug Mode
The error that is shown by the debugger when running in debug mode
The error that is shown by the debugger when running in debug mode
Now if you go back and change the title to something other than Untitled your page will run normally.



View the following video to see how to create a Base Page.
Themes


Themes are a way for you to define a consistent look and feel across your web site. They consist of files and properties that can include:

  • Skins
  • Style Sheets (CSS)
  • Images

When you devleop a theme it will reside in a special directories in your web site. While themes can consist of many different elements at a minimun a theme consists of a skin.


Skins


 

A skin defines properties for the individual ASP.NET controls on your web site. Skin properties are created very similar to the way common controls are marked up but only contain the properties that you want to be part of the theme.  For example, a skin for a Button control might look like this:

<asp:button runat="server" BackColor="lightblue" ForeColor="black" />

Skins are created in files with the extension .skin which you create inside a Theme folder. The can contain markup for a single control or a list of controls. It is also possible for you to create a skin file for each control.

There are basically two types of control skins:

  1. A default skin that is automatically applied to all the controls of the same type when the theme is applied to the page. A control skin is a default skin if it does not have a SkinID attribute. For example, if you create a default skin for a Calendar control, the control skin applies to all Calendar controls on pages that use the theme. (Default skins are matched exactly by control type, so that a Button control skin applies to all Button controls, but not to LinkButton controls or to controls that derive from the Button object.)
  2. A named skin is a control skin with a SkinID property set. Named skins do not automatically apply to controls by type. Instead, you explicitly apply a named skin to a control by setting the control's SkinID property. Creating named skins allows you to set different skins for different instances of the same control in an application.

Style Sheets (CSS)


 

A theme can also include a cascading style sheet (.css file). When you put a .css file in the theme folder, the style sheet is applied automatically as part of the theme.


Resources


 

Themes can also include graphics and other resources, such as script files or sound files. For example, part of your page theme might include a skin for a TreeView control. As part of the theme, you can include the graphics used to represent the expand button and the collapse button.

Typically, the resource files for the theme are in the same folder as the skin files for that theme, but they can be elsewhere in the Web application, in a subfolder of the theme folder for example. To refer to a resource file in a subfolder of the theme folder, use a path like the one shown in this Image control skin:

<asp:Image runat="server" ImageUrl="ThemeSubfolder/filename.ext" />

You can also store your resource files outside the theme folder. If you use the tilde (~) syntax to refer to the resource files, the Web application will automatically find the images. For example, if you place the resources for a theme in a subfolder of your application, you can use paths of the form ~/SubFolder/filename.ext to refer to resource files, as in the following example.


<asp:Image runat="server" ImageUrl="~/AppSubfolder/filename.ext" />


Creating A Theme


 The first thing you need to do to create a theme for your web site is to create a place to put it. This will require adding a folder called App_Themes to your project. Simply right click on the project and select add, ASP.NET Folder, Theme:

An upgrade has been detected. Please login as a Super User (host) to upgrade!

Adding The Theme Folder
You must add a Theme folder to put your themes in.
You must add a Theme folder to put your themes in.

Notice that inside the App_Themes folder a second folder was created. This is the name and folder that will hold your first theme. If you did not give your theme a name it defaults to Theme1. You should provide a descriptive name for your theme. For instance if you are creating a green theme you might want to name the theme green.

 Create a Skin


Now that we have setup our them folder let's create a couple of skin files to be used as part of our theme. To do this, right click on your theme folder (not App_Themes) and select add then New Item and finally select Skin File. Don't Forget to give your skin a name.

Add Skin
Add a Skin to your Themes folder
Add a Skin to your Themes folder

Adding Skin Style


Once you have created the skin file you can add styles to the particular controls. It should be noted that you can have a skin file for each control or put all of the styles inside one skin file.

 Adding style is very similar to adding a control to a web form. Here you simply define the styles that you want and omit the id of the control. Here is an example of a style that will change all buttons forecolor  to Royal Blue and the background to Silver.

 <asp:button runat="server" forecolor="RoyalBlue" backcolor="Silver"/>

The following is an example of a simple theme file:

Skin File Example
Sets the properties for a button and a label control. This will be applied to all Buttons and Labels
Sets the properties for a button and a label control. This will be applied to all Buttons and Labels

Linking the Theme


To get the them to work you need to modify the web.config file. Be careful when you do this because if you mess something up your page may not load. I suggest backing the file up before modifying it.

 Open the web.config file and search down until you find the pages element. Inside this tag add a property theme and set it equal to the name of the theme file your created:

 <pages theme="Theme1">

 Below is a example of the modified web.config file:

Modify the pages element
Add the theme attribute to the pages element within the web.config
Add the theme attribute to the pages element within the web.config
Testing Your Theme

The skin file has style definitions for Labels and Buttons. To test the theme out simply add a Button and Label to the form. Please note that you will not see the effects of the theme until your run your web page. In design mode your controls will look unchanged.

In this example a Button and a Label have been added to the form. Now when the page is ran the theme will be applied to the controls:

Theme Applied
Definitions in the skin file are applied to the Label and Button controls
Definitions in the skin file are applied to the Label and Button controls

Of course these styles are not real appealing and I would hope that anyone with some sense of design could come up with something a little nicer.

 

Video - Creating A Theme


The following video will walk you through creating a them file:

Creating Themes
How to create a theme for your asp.net website
How to create a theme for your asp.net website
Putting it All Together

The following video show how to dynamically change themes through the use if a base page and some helper classes. 

Theme Changer
Class Code For Above Video

The following is the class code Theme and ThemeManager used in the video

Theme Class
Theme class code for theme changer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ThemeChanger
{

    public class Theme
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public Theme(string name)
        {
            Name = name;
        }

    }

}

Theme class code for theme changer
Theme Manager Code
Theme manger class code used to dynamically change themes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.IO;

namespace ThemeChanger
{
    public class ThemeManager
    {
        public static List<Theme> GetThemes()
        {
            DirectoryInfo dInfo = new DirectoryInfo(
              System.Web.HttpContext.Current.Server.MapPath("App_Themes"));
            DirectoryInfo dArrInfo = dInfo.GetDirectories();
            List<Theme> list = new List<Theme>();
            foreach (DirectoryInfo sDirectory in dArrInfo)
            {
                Theme temp = new Theme(sDirectory.Name);
                list.Add(temp);
            }
            return list;
        }
    }
}

Theme manger class code used to dynamically change themes