Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach or Repeater - which is better?

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>

like image 222
Emma Avatar asked Dec 07 '08 10:12

Emma


3 Answers

foreach is the way to go for ASP.NET MVC. Why? i personally avoid any legacy asp:xxx controls .. because they could possibly have the bloat that exists with the webforms model. Secondly, what about all the event delegates you have to wire up? you're starting to mix and match architectures, IMO, so this could seriously lead to real spagetti code with crazy maintenence and support issues. (IMO: DataBinder.Eval == very evil :( :( :( )

The only asp:xxx control i use is the mastpage / content control(because there are no alternatives to it).

Lastly, doing foreach in asp.net mvc is NOT spagetti code, as many people believe. I know i did when i first saw the initial mvc demo's. If anything, it actually makes the UI so much more cleaner than before, imo .. so much more maintainable. IMO, spagetti code is when u have lots of <% .. %> doing business logic and ui logic and (gag) db access. Remember, that's what peeps did in the wild west of asp.net classic :P

Summary

Stick with foreach and avoid using any webform controls - it's simple, very efficient and very possible to do.

like image 156
Pure.Krome Avatar answered Oct 26 '22 05:10

Pure.Krome


foreach is definitely faster, if you don't specifically screw up something. Repeater is 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 makes foreach the only choice.

I personally prefer Repeater for normal situations and foreach for 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.

like image 21
mmx Avatar answered Oct 26 '22 05:10

mmx


I use the extension method repeater from Phil Haack. Best of both worlds. http://haacked.com/archive/2008/05/03/code-based-repeater-for-asp.net-mvc.aspx

like image 22
Craig Avatar answered Oct 26 '22 06:10

Craig