简体   繁体   English

母版页需要知道当前内容页是否未使用ContentPlaceHolder

[英]Master page needs to know if a ContentPlaceHolder hasn't been used by current content page

I have a master page which has several ContentPlaceHolders. 我有一个母版页,其中包含几个ContentPlaceHolders。 Not all of them are used by the current content page all the time. 并非所有内容都一直被当前内容页面使用。 During page rendering the master page needs to set a property when a ContentPlaceHolder wasn't used by the current content page. 在页面渲染期间,当当前内容页面未使用ContentPlaceHolder时,母版页面需要设置一个属性。 Meaning a ContentPlaceHolder might not be referenced by the content page. 意味着内容页面可能未引用ContentPlaceHolder。

What's the best way for the master page to iterate through its ContentPlaceHolders and find out which ones haven't been used by the current content page? 母版页遍历其ContentPlaceHolders并找出当前内容页面尚未使用的内容的最佳方法是什么? Looking for a solution that does not involve any communication from content page to master page. 寻找一种解决方案,该解决方案不涉及从内容页面到母版页面的任何通信。

Do it in the PreRender event of the MasterPage - by this time in the page cycle, all of the controls will be created. 在MasterPage的PreRender事件中执行此操作-到页面周期为止,此时将创建所有控件。

YourMasterPage.master.cs

protected void Page_PreRender(...) {
    HidePlaceholders(this);
}

protected void HidePlaceholders(Control control)
{
     foreach (Control ctrl in control.Controls)
     {
         if (ctrl is ContentPlaceHolder)
         {
            if (ctrl.Controls.Count == 0)
            {
                ctrl.Visible = false;
            }

         }
         else
         {
            if (ctrl.Controls.Count > 0)
            {
                HidePlaceholders(ctrl);
            }
         }

     }
}

Is there a reason not to use default content in your place holders? 是否有理由不在占位符中使用默认内容? Like so: 像这样:

<!-- Site.Master -->
<asp:ContentPlaceHolder ID="SomeCotnent">
    <p>Content here will only appear if it's not overridden in content pages</p>
</asp:ContentPlaceHolder>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM