Conditionally show content the easy way


Yesterday I showed you a neat way to hide/show some content based on authentication level and/or the page mode. The cool thing about it was that whenever the control was hidden, the child controls didn’t get instantiated at all preventing you from any kind of performance penalty. Today, when I read the article myself, it struck me: you could extract a piece of the control that I showed you yesterday and make of it a base class for all kind of conditionally visible content like content visible based on a query string parameter or a value of a field of the current page!

Although the code responsible for showing/hiding the content wasn’t that complex it would be a shame if you copy/paste it while developing multiple controls that show/hide content depends on some condition. The best way to manage this would be to create an abstract base class so that every time that you need a conditionally visible control, all that you need to do is to implement the condition!

The code

[ParseChildren(true)]
public abstract class ConditionallyVisibleControl : Control
{
    public ITemplate ContentTemplate { get; set; }

    public abstract bool ShouldBeVisible { get; }

    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        if (ShouldBeVisible && ContentTemplate != null)
        {
            Control container = new Control();
            ContentTemplate.InstantiateIn(container);
            Controls.Add(container);
        }
    }
}

Although it’s just a couple of lines of code, it’s always a good practice to isolate repeating code. Let’s see what would a control that shows content depending on some query string parameter look like.

public class QueryStringTrimmedControl : ConditionallyVisibleControl
{
    public string Parameter { get; set; }
    public string Value { get; set; }

    public override bool ShouldBeVisible
    {
        get
        {
            bool shouldBeVisible = Page.Request.QueryString[ParameterName] == Value;

            return shouldBeVisible;
        }
    }
}

That’s really all! Then in your Master Page you would use it like:

<Imtech:QueryStringTrimmedControl Parameter="showInfo" Value="1" runat="server">
<ContentTemplate>
...
</ContentTemplate>
</Imtech:QueryStringTrimmedControl>

How simple is that?!

You can use the base ConditionallyVisibleControl class and build all kinds of conditionally visible controls on top of it in just a matter of minutes!

Technorati Tags: SharePoint,SharePoint 2007,SharePoint 2010

Others found also helpful: