2016-12-08 40 views
2

如何方便地访问嵌套母版页中的控件?ASP.NET - 嵌套主页中的FindControl


访问主页控件通常直线前进:

Dim ddl As DropDownList = Master.FindControl("ddl") 

然而,当我的设置如下所述控制无法找到,想必监守控制是content块内:

1 Root Master

<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

尽管我不完全确定为什么你的页面是这样构造的 - 我会建议你通过页面层次结构通过属性公开控件数据,这样你就不必做点符号FindControl(“”)重组和运行时执行。相反,请在母版页上公开属性,在母版页上设置属性,然后从子页面访问它们的类型安全。 –

回答

2

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

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

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继承,像这样使用扩展方法

+1

有点迟来帮助我,但谢谢。似乎是个好主意。 – Obsidian