Ran into a post from Steve Sandersen earlier in which he laments the verbosity of doing things like odd/even parsing in an iterative loop in ASP.NET MVC. Steve proceeds to show an abstract solution which is a great idea for more complex scenarios, but if all you need is odd even type parsing may be a bit of overkill especially since it such a common scenario.
I tend to use a slightly simpler approach for odd even figuring based on a logical variable that’s changed in a loop. Here’s what my version of similar code looks like:
<% bool oddEven = true;
foreach (CodeSnippetListItem snip in snippetList)
{ %>
<div class="<%= (oddEven = !oddEven) ? "evenclass" : "oddclass" %>">
Content goes here...
</div>
<% } %>
That’s not too bad to read as far as tag soup goes. The key is a logical var that is simple ‘not-ed’ – this can be done after the { or as I’ve done here direclty inline of the expression. The only hard part with this code is figuring out whether it starts on odd or even :-}
Another option is to use some client script code – jQuery can make short work of applying classes after the page’s been loaded.
<script type="text/javascript">
$(document).ready(function() {
$(".snippet:odd").addClass("listalternate");
});
</script>
Given the two approaches I think the former is the better choice because I like to keep the display at the point where it’s applied in the HTML or style sheet and just in case JavaScript doesn’t work the display is consistent either way.
Options are good though…
Other Posts you might also like