views:

319

answers:

4

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?

+7  A: 

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.

YeahStu
I recommend this, no tag soup for you!
jfar
http://roshanbh.com.np/2008/03/different-color-alternate-row-jquery.html
Junior Mayhé
+1  A: 

If you want it cleaner I'd recommend writing a custom HtmlHelper extension. I would not use jquery as stu42 suggests simply because I like to look to javascript purely for behavior. Ideally, and hopefully in the not too distant future, you would use pure css for this purpose. Until then, I'd leave it in the markup, as you're currently doing, but with an extension that handles the logic, pulling it out of the aspx.

dustyburwell
Can you provide an example of what this might look like?
YeahStu
+2  A: 

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; }
Perpetualcoder
Works in fire fox, chrome, but not in IE :(
Sly
not even in IE 8 ? O havent tested on IE 8 myself but I imagined it would... service pack !!
Perpetualcoder
Don't work in IE 8 on Win7 x64
Sly
cuz thats high tech stuff :P
Perpetualcoder
A: 

If you don't want to use a class you can set css directly with jquery.

Suppose your table tag is: <table id="tb">..., you just have to set your html as follows:

<head>
<script language="javascript" type="text/javascript" src="jquery-min.js"/>
</head>

<body>
    <script language="javascript" type="text/javascript">
    $(document).ready(function() { 
        $("#tb tr:odd").css("background-color", "#F4F4F8"); 
    });
    </script>

    <table id="tb">
        <tr><th>Id</th><th>Name</th></tr>
        <tr><td>1</td><td>Junior</td></tr>
        <!--more rows here... -->
    </table>
</body>
Junior Mayhé