[收藏]Implementing Master Pages in ASP.NET

 

Implementing Master Pages in ASP.NET

 

Download Master Pages Control and Sample Code:http://www.asp.net/ControlGallery/default.aspx?Category=40&tabindex=2
This sample demonstrates how to implement master pages in ASP.NET.  This is sometimes referred to as Visual Inheritance, Page Inheritance, or Page Templating.

What are master pages?

A lot of sites want to be able to design the layout of their pages in a single place (the Master Page), and then have all the other pages use it, without needing to duplicate any HTML.  For example, a news site would want to have the same header and footer in all their pages, while the actual content of the article changes.  While ASP.NET doesn't directly have a feature to handle this scenario, it is quite easy to achieve the required behavior using a User Control.

What is included in this sample

The most important file is MasterPages.cs, which implements the basic framework that makes Master Pages work.  You should be able to use this code as is (though you can certainly modify it as you wish).  Use mk.bat to build MasterPages.cs.  An example that uses the framework is also included.  It is made up of the files TestMasterPage.ascx and TestPage.aspx.  You can use that as a starting point for your own pages.

How to use this framework

  • The master layout is defined in a User Control (ascx file).  Note that this is quite a departure from the way User Controls are typically used.  In most cases, a User Control renders within a page.  But in this case, we reverse the situation by having the User Control define the Master Page.  The only thing that differentiates a Master Page User Control from a regular one is that it uses one or more tags to define where the per-page content needs to be inserted.  Those tags can have some default content, which is used if the aspx page which uses the ascx master page doesn't define the matching region.
  • Then, the per-page content is defined in Pages (aspx files).  Those Pages need to do a few simple things to use the Master Page:
    • they define a top level tag, with a MasterPageFile attribute pointing to the master page (ascx) file.
    • the tag contains one or more tags to define the customizable content of the Master Page.  Those tags should have an ID that matches the ID of the tag for which they are defining content.
    • the tag should not include any content outside of the tags.  If they do, an error will occur.

      Instructions to build and run the sample

      • Unzip all the files into the root directory of a web application with a bin directory
      • Run mk.bat to build MasterPages.dll into your bin directory
      • Use your browser to request the test page http://localhost/yourtestapp/TestPage.aspx

      Please send feedback and comments to davidebb@microsoft.com

       

    • for which they are defining content.
posted @ 2004-02-22 22:28  dudu  阅读(5423)  评论(4编辑  收藏  举报