Use ContentPlaceHolder’s default content instead of page’s content

asp.netcontentplaceholdermaster-pages

When a page that uses a master page doesn't have an asp:Content control for one of the master page's ContentPlaceHolders, the default content is shown instead. I want to use that default content on a page that does have an asp:Content control for that ContentPlaceHolder.

In the page that uses the master page I want to decide in code whether to use the default content or the page-specific content. How can I show the default content from the master page instead of the content from the asp:Content control for the ContentPlaceHolderID?

For instance, say I have a ContentPlaceHolder for a menu. The default content shows a basic menu. The page builds the menu from a query, but if there's no result for the query I want to show the default menu. By default though, the empty asp:Content control will be shown. How do I get the master page's default content instead?

Best Answer

One way to do it is to clear the controls collection of the placeholder contents in the Page_Load and add your updated menu.

protected void Page_Load(object sender, EventArgs e)
{
    if(needsBetterMenu)
    {
        ContentPlaceHolder holder = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
        holder.Controls.Clear();
        holder.Controls.Add(betterMenu);
    }
}
Related Topic