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>
-
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 makesforeach
the only choice.I personally prefer
Repeater
for normal situations andforeach
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.
-
foreach
is the way to go for ASP.NET MVC. Why? i personally avoid any legacyasp:xxx
controls .. because they could possibly have the bloat that exists with the webforms model. Secondly, what about all theevent 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 themastpage / 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 :PSummary
Stick with
foreach
and avoid using any webform controls - it's simple, very efficient and very possible to do. -
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
Emma : Wouldn't this be faster? <% int i = 0; foreach (var thing in ViewData.Model) { %><%= thing.Name %>
<% i++; }; %> for classes .row0 & .row1 That could be silly - just throwing it out there. -
Here's another option. I have not used this myself, but looks interesting.
-
<p each="var item in ViewData.Model">${item.Name}</p>
Mmm, tasty Spark.
0 comments:
Post a Comment