I am using a <% foreach ...%> loop to list a collection of items on my website.
I want to add a different background color for the style of alternating rows in my list. I have found a way to do this but I am not satisfied with it as it seems like a hack.
Here is what I have done to solve it so far:
<table>
<% int counter = 0;
foreach (var item in Model)
{
counter++;
if (counter % 2 == 0)
{
%>
<tr class="colorfull">
<% }
else
{ %>
<tr>
<% } %>
...
Is there a best practice that I am missing that people are using for this scenario in ASP.NET MVC?
I found this snippet of JQuery code, which I find to be much cleaner.
$(document).ready(function() { $("table tr:nth-child(odd)").addClass("colorfull"); });
I have taken out the counter logic. This JQuery script manipulates the DOM to set the css class of every other row in the foreach loop.
If you are the daring types who wants to dive into CSS3
tr:nth-child(odd) { background-color:#eee; }
tr:nth-child(even) { background-color:#fff; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With