I’m building a website in ASP.Net, using MVC, and need to list a set of results. Both of the following work as I want them to but I’m wondering which is faster, cleaner and/or better – or if another option entirely would be more appropriate?
Note: ViewData.Model is of type IEnumerable<Thing> and I need to display more attributes than Name – I’ve cropped the code for this example.
<% foreach (var thing in ViewData.Model) { %> <p><%= thing.Name %></p> <% }; %>
<% rptThings.DataSource = ViewData.Model; rptThings.DataBind(); %> <asp:Repeater ID='rptThings' runat='server'> <ItemTemplate> <p><%# DataBinder.Eval(Container.DataItem, 'Name') %></p> </ItemTemplate> </asp:Repeater>
foreachis definitely faster, if you don’t specifically screw up something.Repeateris cleaner of course, and more neatly separates UI and logic. Sometimes you need more conditions (other than different look even and odd rows) to render your stuff properly which makesforeachthe only choice.I personally prefer
Repeaterfor normal situations andforeachfor more complex ones.EDIT: I was talking about plain ASP.NET with WebControls. For MVC and even pages that are mostly generated by code, I agree that foreach is more straightforward and cleaner.