ASP.NET 母版页概述
使用 ASP.NET 母版页可以为应用程序中的页创建一致的布局。单个母版页可以为应用程序中的所有页(或一组页)定义所需的外观和标准行为。然后可以创建包含要显示的内容的各个内容页。当用户请求内容页时,这些内容页与母版页合并以将母版页的布局与内容页的内容组合在一起输出。
介绍
母版页(MasterPage)就相当于模板页,挺简单的,没什么好说的。基于母版页的常用的功能有:母版页和内容页之间信息的传递,在内容页中用FindControl方法找到内容页中的控件等。另外,母版页是可以嵌套的。
关键
在内容页的头部加上母版页的强类型引用
<%--创建对母版页的强类型引用,并指定到母版页的虚拟路径--%>
<%@ MasterType VirtualPath="~/MasterPage/MasterPage.master" %>
<%@ MasterType VirtualPath="~/MasterPage/MasterPage.master" %>
1、内容页传递数据到母版页 - 母版页创建一个公共方法,然后内容页通过“Master.方法”来调用这个公共方法
2、母版页传递数据到内容页 - 母版页创建一个公共事件来传递数据,然后内容页处理这个事件
3、内容页中用FindControl方法找到内容页中的控件 - 用“Master.FindControl("ContentPlaceHolder1").FindControl("你要查找的控件ID")”来查找
4、嵌套母版页 - 说起来麻烦,看源码吧
示例
主母板页
Site.master
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="Site" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>重新过一遍ASP.NET 2.0(C#)</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>重新过一遍ASP.NET 2.0(C#)</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
次母板页
MasterPage/MasterPage.master
<%@ Master Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="MasterPage.master.cs" Inherits="MasterPage_MasterPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<p>
我是一个嵌套母版页
</p>
<p>
母版页中的内容
<asp:DropDownList ID="ddlMaster" runat="server" DataSourceID="XmlDataSource1" DataTextField="text"
DataValueField="value" AutoPostBack="True" OnSelectedIndexChanged="ddlMaster_SelectedIndexChanged">
</asp:DropDownList><asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Config/DropDownListData.xml">
</asp:XmlDataSource>
</p>
<p>
内容页中的内容
<asp:ContentPlaceHolder ID="cph" runat="Server" />
</p>
</asp:Content>
CodeFile="MasterPage.master.cs" Inherits="MasterPage_MasterPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<p>
我是一个嵌套母版页
</p>
<p>
母版页中的内容
<asp:DropDownList ID="ddlMaster" runat="server" DataSourceID="XmlDataSource1" DataTextField="text"
DataValueField="value" AutoPostBack="True" OnSelectedIndexChanged="ddlMaster_SelectedIndexChanged">
</asp:DropDownList><asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Config/DropDownListData.xml">
</asp:XmlDataSource>
</p>
<p>
内容页中的内容
<asp:ContentPlaceHolder ID="cph" runat="Server" />
</p>
</asp:Content>
MasterPage/MasterPage.master.cs
内容页
MasterPage/Test.aspx
MasterPage/Test.aspx.cs