简体   繁体   中英

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. 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. Meaning a ContentPlaceHolder might not be referenced by the content page.

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? 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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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