I have a master page with a content control. I want it to do something specific during load if a particular content place holder has been used.
APageWithContent.aspx
<asp:Content ContentPlaceHolderID="myContent" runat="server">
<div>hello world!</div>
</asp:Content>
MasterPage.aspx
<asp:ContentPlaceHolder ID="myContent" runat="server" />
It's optional on the pages that use the master whether they provide any content for this placeholder.
I want to be able to tell during the load and prerender events in the master page whether there is a content for my placeholder on the current page.
MasterPage.aspx.cs
void Page_Init( object sender, EventArgs e )
{
if( /* myContent is populated */ )
//do something
}
Anyone know how to discern this?
In WebForms you can check the controls:
myContent.Controls.Count > 0
But for MVC views this always appears to be 0.
Best Answer
I did this by just checking myContent.Controls.Count.. However, you obviously need to take into consideration any default controls that might be added.
For example, if you have your content placeholder defined as:
Then you will get a
LiteralControl
in the controls collection containing "\r\n" (since the line break in the definition is parsed).So, if you remove that and define as:
Then you can do the check in the master page load:
Just make sure you test the code to make sure you are actually checking for content added by the content pages, and not any default content defined in the master.
UPDATE
Following edit saying this problem is MVC-only I can confirm I am unable to replicate. I used the same code as above in an MVC app and it worked exactly as expected & described.
Can you post some sample code of what you have in place?
FYI - Here is the [working] code:
Site.Master
Index.aspx