Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Striped table rows in ASP.NET MVC (without using jQuery or equivalent)

When using an ASP.NET WebForms ListView control to display data in an HTML table I use the following technique in to "stripe" the table rows:

<ItemTemplate>
    <tr class="<%# Container.DisplayIndex % 2 == 0 ? "" : "alternate" %>">
        <!-- table cells in here -->
    </tr>
</ItemTemplate>

With the following CSS:

tr.alternate
{
    background-color: #EFF5FB;
}

I have just gone through the ASP.NET MVC Movie Database Application tutorial and learnt that in MVC-land table rows can be (must be?) constructed as follows:

<% foreach (var item in Model) { %>
    <tr>
        <td>
            <%= Html.Encode(item.Title) %>
        </td>
        <!-- and so on for the rest of the table cells... -->
    </tr>
<% } %>

What can I add to this code to stripe the rows of my table?

Note: I know that this can be done using jQuery, I want to know if it can be done another way.

Edit

If jQuery (or equivalent) is in your opinion the best or most appropriate post, I'd be interested in knowing why.

like image 931
Richard Ev Avatar asked Apr 16 '09 14:04

Richard Ev


2 Answers

Another option that doesn't involve lambdas and is a bit cleaner than what you got working might be this...

<% int i=0; foreach (var item in Model) { %>
    <tr class="<%= i++ % 2 == 0 ? "alternate" : "" %>">
        <td>
            <%= Html.Encode(item.Title) %>
        </td>
        <!-- and so on for the rest of the table cells... -->
    </tr>
<% } %>
like image 183
Joel Mueller Avatar answered Oct 10 '22 02:10

Joel Mueller


What about an extension method?

public static void Alternate<T>(this IEnumerable<T> items, Action<T, bool> action)
{
    bool state = false;
    foreach (T item in items)
        action(item, state = !state);
}

This way you could say:

<% movies.Alternate((movie, alt) => { %>
  <tr class="<%= alt ? "alternate" : "" %>">
    <td>
        <%= Html.Encode(movie.Title) %>
    </td>
    <!-- and so on for the rest of the table cells... -->
  </tr>
<% }); %>

Edit, additionally if you want the index, you can use an extension method like this:

public static void Each<T>(this IEnumerable<T> items, Action<T, int> action)
{
    int state = 0;
    foreach (T item in items)
        action(item, state++);
}
like image 34
meandmycode Avatar answered Oct 10 '22 02:10

meandmycode