【问题标题】:ASP.NET - FindControl in nested master pageASP.NET - 嵌套母版页中的 FindControl
【发布时间】:2016-12-08 11:01:54
【问题描述】:

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


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

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 块中访问控件吗?

【问题讨论】:

  • 虽然我不完全确定您的页面为何采用这种结构 - 我建议您通过页面层次结构通过属性公开控件数据,因此您不必执行点符号 FindControl( "") 容易受到重组和运行时异常的影响。而是在母版页上公开属性,在母版页上设置属性,然后从子页访问它们的类型安全。

标签: c# asp.net vb.net master-pages


【解决方案1】:

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

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
}

【讨论】:

  • 帮助我有点晚了,但谢谢。似乎是个好主意。
猜你喜欢
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-19
相关资源
最近更新 更多