ASP.NET - 在嵌套母版页中查找控件

ASP.NET - FindControl in nested master page

如何方便地访问嵌套母版页中的控件?


访问母版页控件通常很简单:

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 块中直接访问该控件?

这是一个可以处理任意数量的嵌套级别的扩展方法:

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 的任何 class 的扩展方法,如下所示:

DropDownList ddl = (DropDownList)Page.Master.FindInMasters("ddl");
if (ddl != null)
{
    // do things
}