您的位置:首页 > 编程语言 > ASP

ASP.NET 2.0 之 Master Page 学习(2)

2008-10-20 14:19 549 查看
1. 页面请求的次序

当用户请求一个用 Master Page 构建的页面时,各种事件发生的次序如下:

Master Page 子控件初始化;
内容页面子控件初始化;
Master Page 初始化;
内容页面初始化;

内容页面 Page_Load;
Master Page 的 Page_Load;
Master Page 子控件加载;
内容页面子控件加载;

注意点:

因为内容页面的 Page_Load 先于 Master Page 的 Page_Load,所以,如果要访问 Master Page 里的服务器控件,则必须在内容页面的 Page_LoadComplete 方法里书写代码。

2. 访问 MasterPage 中的属性和控件。

用 Master 属性来访问。

a. 假设 MasterPage 中有一个 Label1, 那么在内容页面可以这样:

protected void Page_LoadComplete(object sender, EventArgs e)
{
string text = (Master.FindControl("Label1") as Label).Text;
}

页面加载的次序:

要获取在 MasterPage 的 Page_Load 里面设定的值,必须在内容页面的 Page_LoadComplete 中来写。

前面提到的 FindControl() 方法来查找 MasterPage 中的控件,是一种后期绑定的做法,一般是不安全的。因为这取决于 MasterPage 中是否存在这个 tag,如果被删除了,则会导致错误。
比较好的做法是,在 MasterPage 中用属性封装对他的控件的访问;如果用 FindControl(), 则总是检查其结果是否为 null.

3. 指定 MasterPage 中的默认内容

直接在 <asp:ControlPlaceHolder /> 标签之间指定即可。
如果子页面不重新指定,则会采用该默认内容。

4. 编程的方式指定 Master Page

protected void Page_PreInit(object sender, EventArgs e)
{
Page.MasterPageFile = "~/x.master";
}

5. 嵌套的 Master Page

Master Page 可以继承自更高层次的 Master Page. 但是在 VS2005 中创建这种子 Master Page 的时候,不会有默认的支持。
假设有了一个 A.master,
我们现在先创建一个普通的 B.master,
然后删除其中除了 Page directive 的其他部分。
把 Page Directive 修改为如下,并加入自己要定义的 PlaceHolder:

<%@ Master MasterPageFile="~/A.master" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="server">
Hello!
<asp:ContentPlaceHolder ID="ContentPlaceHolder2" Runat="server">
</asp:ContentPlaceHolder>
</asp:Content>

用嵌套的模板产生的子页面将不能采用 VS2005 的 design 模式。

6. 容器特定的 Master Pages

为了能兼容不同的浏览器,asp.net 2.0 支持多个 Master Page. 在运行时将自动加载合适的 Master Page.

语法如下:

<%@ Page Language="VB" MasterPageFile="~/Abc.master"
Mozilla:MasterPageFile="~/AbcMozilla.master"
Opera:MasterPageFile="~/AbcMozilla.master" %>

7. 使用缓存

只有在内容页面才可以使用如下的 directive 指定缓存:

<%@ OutputCache Duration="10" Varybyparam="None" %>

(这个指令让服务器在内存里缓存该页面 10 秒钟)

如果对 Master Page 指定该指令,本身并不会引发错误。但是当他的子页面下一次来获取其 Master Page 的时候,如果这时 Master Page 已经过期,则会引发一个错误。
所以实际上只能对子页面指定缓存。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: