Nested ASP Repeaters without a line of code

Recently I came across a little task, which required listing a few question topics with all of its questions. Since there was only a few topics and each topic have only few questions thought I will solve that with nested repeater controls, combined with LinqDataSource. Whit that I didn’t needed to write a single line of code in code behind, just markups. This makes the code behind much clearer, and it’s easy to understand in a blink of an eye.

Here is an example using the good old Northwind sample database.

<asp:Repeater ID="rptCategories" runat="server" DataSourceID="ldsCategories">
        <ItemTemplate>
            <div style="background-color: Navy; color: White; font-weight: bold;">
                <asp:Label ID="lblCategoryName" runat="server" Text='<%# Eval("CategoryName") %>' />
                </div>
            <asp:HiddenField ID="hfCoategoryId" runat="server" Value='<%# Eval("CategoryID") %>' />            
            <asp:Repeater ID="rptProducts" runat="server" DataSourceID="ldsProducts">
                <ItemTemplate>
                    <asp:Label ID="lblProductName" runat="server" Text='<%# Eval("ProductName") %>' />
                    <asp:HiddenField ID="hfProductID" runat="server" Value='<%# Eval("ProductID") %>' />
                </ItemTemplate>
                <SeparatorTemplate>
                    <br />
                </SeparatorTemplate>
            </asp:Repeater>
            <asp:LinqDataSource ID="ldsProducts" runat="server" 
            ContextTypeName="WebRepeater.NorthwindEntities" TableName="Products" 
            Select="new(ProductName, ProductID)" Where="CategoryID=@CatID">
                <WhereParameters>
                    <asp:ControlParameter ControlID="hfCoategoryId" Type="Int32"
                     DefaultValue="1" Name="CatID" />
                </WhereParameters>
            </asp:LinqDataSource>
        </ItemTemplate>
        <SeparatorTemplate>
            <br />
            <br />
        </SeparatorTemplate>
    </asp:Repeater>
    <asp:LinqDataSource ID="ldsCategories" runat="server" TableName="Categories"
    ContextTypeName="WebRepeater.NorthwindEntities" Select="new(CategoryID, CategoryName)" />

Leave a comment