rails:ConditionalRender - still trying to get WebForms to work right

time to read 3 min | 466 words

Well, as it turns out, there are some things that you can do to make WebForms more palatable. Smart use of ITemplate and some additional magic can take you a fairly long way. I am still severely limited (splitting behavior between markup & code behind is extremely annoying) in what I can do, but it  is good to know that it is possible:

<rails:ConditionalRenderer runat="server" 
    Condition="<%# ((Policy)Container.DataItem).Expired %>"
    DataItem="<%# Container.DataItem %>" >
    <WhenTrue>
        Policy has expired!
    </WhenTrue>    
    <WhenFalse>
        Policy is valid until <%# Eval("ExpiryDate") %>
    </WhenFalse>
</rails:ConditionalRenderer>
 
I am using it inside a repeater to keep the presentation logic in a single place.
 
The code to make this happen is something like this (typed from memory, you need about 80 lines to get it right).
 
[ParseChildren(true)]
public class ConditionalRenderer : Control, INamingContainer
{
    public bool Condition { get { .. } set { .. } }

    [Templatecontainer(ConditionalRenderer)]
    public ITemplate WhenTrue { get { .. } set { .. } } 
    [Templatecontainer(ConditionalRenderer)]
    public ITemplate WhenFalse { get { .. } set { .. } }

    public object DataItem { get { .. } set { .. } }
    
    public override void EnsureChildControls()
    {
        if (Condition)
            WhenTrue.InstansiateIn(this);
        else
            WhenFalse.InstansiateIn(this);
    }
}