ASP.Net 提供了母版页方便了网站的整体布局,但是由于不同的用户权限需要对母版页的功能做适当的修改,以适应不同的用户的使用。这就需要在内容页中对母版页进行操作,进行通信。
在母版页前台设计代码为:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="母版Label"></asp:Label>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="母版Label"></asp:Label>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
母版页的后台代码定义公有方法或属性,方法体中对母版页中的控件进行更改,代码如下:
View Code
1 public string MyLabel
2 {
3 set
4 {
5 this.Label1.Text = value;
6 }
7 get
8 {
9 return this.Label1.Text;
10 }
11 }
2 {
3 set
4 {
5 this.Label1.Text = value;
6 }
7 get
8 {
9 return this.Label1.Text;
10 }
11 }
在内容页的前台设计代码为:
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ MasterType TypeName="MasterPage" %><!--千万别漏了这句-->
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
</asp:Content>
<%@ MasterType TypeName="MasterPage" %><!--千万别漏了这句-->
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
</asp:Content>
之后内容页就可以修改母版页的控件了
protected void Button1_Click(object sender, EventArgs e)
{
this.Master.MyLabel = "内容页与母版页通讯";//修改母版页
}
{
this.Master.MyLabel = "内容页与母版页通讯";//修改母版页
}