Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style alternating rows in asp.net mvc

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?

like image 690
YeahStu Avatar asked Oct 19 '09 02:10

YeahStu


2 Answers

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.

like image 60
YeahStu Avatar answered Nov 09 '22 19:11

YeahStu


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; }
like image 30
Perpetualcoder Avatar answered Nov 09 '22 19:11

Perpetualcoder