grenade
grenade

Reputation: 32179

How do I alternate table row colors in asp.net mvc using jquery?

Probably a dumb question but I'm new to MVC and jQuery. I want to alternate the row colors of my tables and I've decided that I'm going to use jQuery to do it. I know that I could write an extension method (http://haacked.com/archive/2008/08/07/aspnetmvc_cycle.aspx), etc but after reading SH's comment on the article at http://haacked.com/archive/2008/05/03/code-based-repeater-for-asp.net-mvc.aspx I've picked jQuery as the solution I want to implement.

I want to implement the method described at http://www.packtpub.com/article/jquery-table-manipulation-part2 but I haven't figured out where to put the initial jQuery call (eg: $(document).ready(function() {...});

Like I said, I'm new to jQuery...

Upvotes: 4

Views: 7835

Answers (3)

tvanfosson
tvanfosson

Reputation: 532455

Be aware that if you use jQuery and the user has javascript turned off, your UI is not going to get styled the way you want. You may want to consider doing the assignment of CSS classes for styling in the view code itself.

   @{ var alternating = false;
      foreach (var row in Model) {
          <tr class='@(alternating ? "alternating-row" : "normal-row")'>
          ...
          alternating = !alternating;
   }     

Upvotes: 11

Ken Browning
Ken Browning

Reputation: 29091

You can accomplish this by setting a class on all the even rows of a table.

<html>
    <head>
        <title>Example Title</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('tr:even').addClass('alt-row-class');
            });
        </script>
    </head>
    <body>...</body>
</html>

Then apply style to that class using standard css:

.alt-row-class { background-color: green; }

A commenter correctly points out that you might wish to play around with the selector (tr:even) to get the results you want relative to tbody, thead and tfoot elements.

Upvotes: 19

Chad Birch
Chad Birch

Reputation: 74548

If you use the jQuery plugin Tablesorter, it has a built-in "widget" for this called "zebra" (among all of its other functionality).

Upvotes: 1

Related Questions