Search code examples
c#asp.netasprepeater

Using foreach with ASP.NET view engine inside a ASP: Repeater is not working


I have a ASP: Repeater, I need to use a foreach loop using ASP.NET view engine

But I have ran into a issue.

Here is the code inside the repeater:

           <%# cart = (CartDTO)Container.DataItem %>

                      <% foreach (var item in cart.Products)
                       { %> 
                        <p><%= item.Title %></p>
                      <% }%>

The problem here is that nothing renders out. I have found the issue. I have to use <%# instead of <%= that will render it. But the issues is that <%# does not work in a ASP: Repeater. Item becomes "Cannot resolve "Item" symbol.

Is there any solutions for this?


Solution

  • I do not think repeater will easily understand such snippet inside the item template. In general C# code in ASP.NET page markup should not be used for things more complicated than "output this value to the page".

    You better off creating a nested repeater for such task:

    <asp:Repeater runat="server" DataSource='<%# ((CartDTO)Container.DataItem).Products %>'>
        <ItemTemplate>
            <p> <%# Eval("Title") %></p>
        </ITemTemplate>
    </asp:Repeater>