External ITemplates and Hierarchical Databinding

Ever wish you could declare a template outside of the control you were defining the template for? We always get requests to have FormView's InsertItem template fall back on the EditItemTemplate and vice versa. That would be easy if we could do what was mentioned above.

Consider:

<asp:FormView ID="myFormView" runat="server" DefaultMode="Edit" 
    EditItemTemplate="editTemplate" 
    InsertItemTemplate="editTemplate">
</asp:FormView>
 
<asp:Template runat="server" ID="editTemplate">
    Name : <asp:TextBox runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
    Age : <asp:TextBox runat="server" Text='<%# Bind("Age") %>'></asp:TextBox>
</asp:Template>

Then you could do things like hierarchical databinding pretty easily; just define the template in terms of itself. Today, properties typed as ITemplate are treated specially by the ASP.NET parser, and what is written above will not work.

How would you do this with what asp.net offers now? Well check out this sample:

<cc:SpecialRepeater runat="server" ItemTemplateID="folderTemplate" DataSource='<%# GetDirectories() %>' />        
<cc:Template runat="server" ID="folderTemplate">
    <ItemTemplate>
        <ul>
            <li>
                <%# Eval("Name") %>
                <cc:SpecialRepeater runat="server" DataSource='<%# GetDirectories((string)Eval("FullName")) %>' ItemTemplateID="folderTemplate" />
                <ul>
                    <cc:SpecialRepeater runat="server" DataSource='<%# GetFiles((string)Eval("FullName")) %>' ItemTemplateID="fileTemplate" />
                </ul>
            </li>
        </ul>
    </ItemTemplate>
</cc:Template>
 
<cc:Template runat="server" ID="fileTemplate">
    <ItemTemplate>
        <li> <%# Eval("Name") %>
        </li>
    </ItemTemplate>
</cc:Template>

We have a SpecialRepeater that understands how to hookup template properties through their ID (it's just FindControl) and a Template control that defines our file template and folder template. We define the folder template in terms of itself. Can you think of any more uses for something like this?

Get the code here.

What do you think?

4 Comments

Comments have been disabled for this content.