[英]asp.net how to change a control which is in parent master page, from content page with nested master pages
[英]Can content page use ContentPlaceHolderID of master parent of its master page (nested master pages)
我有一個3級嵌套母版頁和一個內容頁面。 parent1是頂級父級,parent2是parent3的父級,parent3是內容頁面的父級。
我收到錯誤' Cannot find ContentPlaceHolder xxx...
',其中xxx是ContentPlaceholder。 它位於parent2中,內容頁面正在嘗試填充它。
內容頁面只能使用他們的直接父ContentPlaceHolders,還可以使用任何更高版本的母版頁?
有一種方法可以做到這一點,但如果您依賴占位符中的任何默認內容,則在某些情況下會出現輕微問題。
在您的示例中,您有Parent1.master
:
<div id="content">
<h1>Lorem Ipsum, from Parent1</h1>
<asp:ContentPlaceHolder ID="cphContent" runat="server">
<p>I am default content from Parent1...</p>
</asp:ContentPlaceHolder>
</div>
而且你還有一個嵌套的Parent2.master
,它使用Parent1中的占位符:
<asp:Content ContentPlaceHolderID="cphContent" runat="server">
<h2>I am some specific stuff from Parent2...</h2>
<asp:ContentPlaceHolder ID="cphContent" runat="server">
<p>I am default content from within Parent2!</p>
<p>We want to create another, nested CPH so that Parent3 can use it!</p>
<p>(It is seemingly OK that we can use the same ID for this CPH<br />
in Parent2 that we did originally in Parent1.)</p>
</asp:ContentPlaceHolder>
</asp:Content>
所以現在Parent3.master
可以使用Parent3.master
中的占位符。 (還提供另一個占位符,供最終內容頁面使用!)這里是:
<asp:Content ContentPlaceHolderID="cphContent" runat="server">
<h3>Hello from Parent3!</h3>
<asp:ContentPlaceHolder ID="cphContent" runat="server">
<p>I am more default text in yet another nested placeholder</p>
</asp:ContentPlaceHolder>
</asp:Content>
您呈現的內容頁面如下所示:
<div id="content">
<h1>Lorem Ipsum, from Parent1</h1>
<h2>I am some specific stuff from Parent2...</h2>
<h3>Hello from Parent3!</h3>
<p>I am the plugged-in content, from the content page!</p>
</div>
關於這種方法的一個很酷的事情,以及為什么我們可能希望在整個繼承鏈中對這些嵌套的CPH使用相同的名稱,是因為您的最終內容頁面可能會從使用任何父母版頁1到3更改而無需更改任何內容否則,只要他們期望找到一個叫做cphContent
東西來消費。
好的,所以現在你已經看到了有趣的部分,但我唯一提到的可能是一個問題,就是如果你試圖讓任何“默認”文本涓涓細流到任何一個大孩子。 這樣,我的意思是如果您的內容頁面沒有為“cphContent”占位符提供任何內容,那么將只使用上一個母版頁的默認值。 Parent1.master
的默認值基本上不會超過Parent2。 (雖然您當然可以使用Parent3中的默認值。)可能有一種方法可以以編程方式執行此操作,但“開箱即用”這似乎可以讓您按照您的要求執行操作,如果您可以忍受此警告。
祝你好運!
我相信內容頁面只能使用直接父級的ContentPlaceHolder。
獲取主頁面上的控件值在運行時,主頁面與內容頁面合並,因此主頁面上的控件可供內容頁面代碼訪問。 (如果母版頁包含ContentPlaceHolder控件中的控件,則如果內容頁面中的內容控件覆蓋了這些控件,則無法訪問這些控件。)控件不能作為母版頁成員直接訪問,因為它們受到保護。 但是,您可以使用FindControl方法在母版頁上查找特定控件。 如果要訪問的控件位於母版頁上的ContentPlaceHolder控件內,則必須先獲取對ContentPlaceHolder控件的引用,然后調用其FindControl方法以獲取對該控件的引用。
以下示例顯示如何獲取對母版頁上控件的引用。 引用的控件之一是在ContentPlaceHolder控件中,而另一個不是。
Visual Basic復制代碼'獲取對ContentPlaceHolder中的TextBox控件的引用
Dim mpContentPlaceHolder As ContentPlaceHolder
Dim mpTextBox As TextBox
mpContentPlaceHolder = _
CType(Master.FindControl("ContentPlaceHolder1"), _
ContentPlaceHolder)
If Not mpContentPlaceHolder Is Nothing Then
mpTextBox = CType(mpContentPlaceHolder.FindControl("TextBox1"), _
TextBox)
If Not mpTextBox Is Nothing Then
mpTextBox.Text = "TextBox found!"
End If
由於您要查找嵌套內容占位符,因此您可能必須找到父級,然后使用該實例查找子級
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.