Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if ContentPlaceHolder is empty?

Tags:

c#

asp.net

How to check if ContentPlaceHolder is absolutely empty?

In the ContentPlaceHolder have text only, without tags and controls.

Example Page.Master:

<asp:ContentPlaceHolder runat="server" ID="Content" />

Example Test.aspx:

<asp:Content runat="server" ContentPlaceHolderID="Content">
    Custom text without controls. Content.Controls.Count is 0 and Content.HasControls is false.
</asp:Content>

What I need to do is that when the placeholder is empty put a default content is in another control.

Overwrite tried twice for the same placeholder but I get error when dynamic load.

like image 407
e-info128 Avatar asked Aug 20 '13 21:08

e-info128


2 Answers

You can implement a method that will render the content control into a string, then check the string to find wheahter it contains any non-white space chars:

private bool HasContent(Control ctrl)
{
    var sb = new System.Text.StringBuilder();
    using (var sw = new System.IO.StringWriter(sb)) 
    {
        using(var tw = new HtmlTextWriter(sw))
        {
            ctrl.RenderControl(tw);
        }
    }

    var output = sb.ToString().Trim();

    return !String.IsNullOrEmpty(output);
}

protected void Page_PreRender(object sender, EventArgs e)
{
    var placeholder = Master.FindControl("FeaturedContent");
    var hasContent = HasContent(placeholder);
}
like image 177
defrost Avatar answered Nov 14 '22 16:11

defrost


You need to find the ContentPLaceHolder on the master page first. Then you can cast the first control(which always exists) to LiteralControl and use it's Text property.

So this works as expected from Page_Load of the content-page:

protected void Page_Load(object sender, EventArgs e)
{
    var cph = Page.Master.FindControl("Content") as ContentPlaceHolder;
    if (contentPlaceHolder != null)
    {
        string textualContent = ((LiteralControl) cph.Controls[0]).Text;
        if (string.IsNullOrEmpty(textualContent))
        {
            // ...
        }
    }
}
like image 1
Tim Schmelter Avatar answered Nov 14 '22 18:11

Tim Schmelter