2016-12-08 39 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