如何在嵌套母版页中方便地访问控件?
访问母版页控件通常是直截了当的:
Dim ddl As DropDownList = Master.FindControl("ddl")
然而,当我的设置如下时,无法找到控件,可能是因为控件在content
块内:
1根大师
<asp:ContentPlaceHolder ID="cphMainContent" runat="server" />
2嵌套大师
<%@ Master Language="VB" MasterPageFile="~/Root.master" AutoEventWireup="false" CodeFile="Nested.master.vb" Inherits="Nested" %>
<asp:Content ID="MainContent" ContentPlaceHolderID="cphMainContent" runat="server">
<asp:DropDownList ID="ddl" runat="server" DataTextField="Text" DataValueField="ID"/>
</asp:Content>
3内容页面VB.NET
Dim ddl As DropDownList = Master.FindControl("ddl")
解决方法
通过遍历树找到根内容占位符cphMainContent
,然后在其中查找控件,我找到了一个解决方案。
cphMainContent = CType(Master.Master.FindControl("cphMainContent"), ContentPlaceHolder)
Dim ddl As DropDownList = cphMainContent .FindControl("ddl")
然而,这个解决方案似乎非常迂回且效率低下。
是否可以直接从母版页的content
块中访问控件?
答案 0 :(得分:2)
这是一个可以处理任意数量嵌套级别的扩展方法:
public static class PageExtensions
{
/// <summary>
/// Recursively searches this MasterPage and its parents until it either finds a control with the given ID or
/// runs out of parent masters to search.
/// </summary>
/// <param name="master">The first master to search.</param>
/// <param name="id">The ID of the control to find.</param>
/// <returns>The first control discovered with the given ID in a MasterPage or null if it's not found.</returns>
public static Control FindInMasters(this MasterPage master, string id)
{
if (master == null)
{
// We've reached the end of the nested MasterPages.
return null;
}
else
{
Control control = master.FindControl(id);
if (control != null)
{
// Found it!
return control;
}
else
{
// Search further.
return master.Master.FindInMasters(id);
}
}
}
}
使用继承自System.Web.UI.Page的任何类的扩展方法,如下所示:
DropDownList ddl = (DropDownList)Page.Master.FindInMasters("ddl");
if (ddl != null)
{
// do things
}