如何使用 MasterPage

1. 创建 MasterPage,后缀名 .master, 如 x.master.
    其中用 <asp:ContentPlaceHolder /> 定义空位。如:

    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" Runat="Server">
    </asp:ContentPlaceHolder>


2. 创建内容页面。
    在 NewItem 对话框里选择 "select master page", 选择上一步创建的 MasterPage.
    产生的代码里, MasterPageFile 属性指定了 MasterPage 的位置:

    <%@ Page Language="VB" MasterPageFile="~/x.master" Title="无标题页面" %>

    页面里用 <asp:Content /> 来添加内容到对应的空位:

    <asp:Content ID="Content1" ContentPlaceHolderId="ContentPlaceHolder1" Runat="Server">
        内容
    </asp:Content/>

    内容页面没有 <form id="form1" runat="server">


3. 利用 MasterPage 可以使用多种语言来编写一个页面的各个部分。


4. 除了在 <%@ Page %> 里面指定 MasterPage, 也可以在 web.config 指定:

    <configuration>
        <system.web>
            <pages masterPageFile="~/x.master" />
        </system.web>
    </configuration>

    这样定义后,如果创建 Page 时选择了 master page, 则在 <%@ Page %> 里面不需要指定即可使用该 MasterPage.
    其他页面要使用不同的 MasterPage 的话,只要用第一种方法在 Page directive 里面明确的覆盖 web.config 里的设置即可。

    可以仅对一组 pages 指定 MasterPage. 下例利用 web.config 的 location 元素,设定了 Admin 目录下的页面采用的不同的 MasterPage.

    <configuration>
        <location path="Admin">
            <system.web>
                <pages masterPageFile="~/y.master" />
            </system.web>
        </location>
    </configuration>


5. 在内容页面如何设定 Page 的 Title ?

    默认情况下,Title 在 MasterPage 中指定后,其他具体页面就都使用这个 Title.
    在具体页面,可以有两个办法修改 Title:
   
    a. <%@ Page Title="test" %>

    b. 代码中:

        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            Master.Page.Title = "Hello";
        }