ASP.NET中子页面反问母版页控件(嵌套母版页)

现有两个母版页First和Second,同时在Second中使用了模板First,然后在一个普通页面中使用了Second,我们需要在这个普通的页面中访问Second中的一个控件(这里使用的是Button):

First.master,

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="First.master.cs" Inherits="JQueryApplication.First"%>

<!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:ContentPlaceHolder ID="FirstContent" runat="server">

</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>

Second.master;

可以看到模板二使用了模板First,同时在模板Second中添加了一个Button,用于在子页面访问

<%@ Master Language="C#" MasterPageFile="~/First.Master" AutoEventWireup="true" CodeBehind="Second.master.cs"
Inherits
="JQueryApplication.Second"%>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="FirstContent" runat="server">
模板二
<asp:Button ID="ButtonTest" runat="server" Text="Button"/>
<div>
<asp:ContentPlaceHolder ID="SecondContent" runat="server">

</asp:ContentPlaceHolder>
</div>
</asp:Content>


这时候看下 模板Second的设计效果:

很简单的效果。

子页面代码:

子页面更加简单,就是仅仅使用了Second的模板,然后添加了一个按钮,在按钮的事件中获得Second中的Button。

<%@ Page Title="" Language="C#" MasterPageFile="~/Second.master" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="JQueryApplication.WebForm2"%>
<asp:Content ContentPlaceHolderID="SecondContent" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button"
onclick
="Button1_Click"/>
</asp:Content>


看下按钮事件中的代码:

this.Master.Master.FindControl("FirstContent").FindControl("ButtonTest") as Button;

没错,就是这样子,this.Master得到的是当前子页面的模板,也就是模板Second,this.Master.Master得到的是Second的模板,也就是First模板,由于按钮Button

是在Second中的FirstContent(模板FirstContentPlaceHolderId)中的,所以需要回到模板First才能访问得到,所以需要使用this.Master.Master.FindControl来找到

对应的控件。



原文地址:https://www.cnblogs.com/ListenFly/p/2258569.html