如何方便地访问嵌套母版页中的控件?
访问母版页控件通常很简单:
Dim ddl As DropDownList = Master.FindControl("ddl")
但是,当我的设置如下时,找不到控件,可能是因为控件位于 content
block 内:
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
block 中访问该控件?
最佳答案
这是一个可以处理任意数量的嵌套级别的扩展方法:
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
}
关于c# - ASP.NET - 嵌套母版页中的 FindControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41037854/