This post was inspired by a comment I saw on another person's blog (which I couldn't find for the life of me, so no linky for them). The comment was in regards to Ruby on Rails use of pure ruby code in the .rhtml view files, and how this was seen as a bad thing. I've written a similar post on my personal blog but I thought my point was worth bringing up again.
How many of you faithful devlicio.us readers would cringe at the sight of the following code snippet embedded within an aspx page?
<% foreach( Item item in LineItems ){ %>
<p> <%= item.Name %> </p>
<% } %>
On first glance, it looks bad because sometime in the past we were told that embedding business logic in the view is bad. But I'd urge you to look again. Is there actually any business logic in the above snippet? There's none, actually. We're just iterating over a list of Items and printing a property out to the rendered markup. We could accomplish the same thing with a repeater like so:
<asp:Repeater id="repeater" runat="server">
<itemtemplate>
<p><%# Eval("Name") %>
</itemtemplate>
</asp:Repeater>
Which one is easier to read? It's pretty subjective... The repeater declaration happens to look just like html or xml markup, so it blends in nicely with any other markup that may appear in our page. This blending can be seen as a good thing, or a bad thing if you like to be able to instantly see any dynamic stuff at a glance. The problem with repeaters it can be hard to see exactly what you're iterating over without also looking into the code-behind. The plus side is that you get nice support for alternating item templates, which can quickly make an embedded foreach look ugly.
The real question is, does using a control like the repeater prevent you from sticking business logic in your views? The answer is no, it doesn't.
Just something to think about.
Posted
10-25-2006 6:50 PM
by
Jeff Perrin