Alternating row colours on tabular data is one of the most common data visualisation styles a web developer has to implement. Almost every project I have built required tabular data, and alternating row colours were key to the clean, easily readable presentation of that data.
However, it quickly becomes tiresome writing the logic to work out which rows are odd/even and change css classes on every table/project, not to mention it breaks the DRY principle. A further issue arises from the MVC pattern’s recommendation that views should be dumb and have low cyclomatic complexity.
To get around both these issues, and in the process gain an abstracted, reusable method of alternating the row colours we can create an extension method. This extension method, when implemented against the IList interface, allows for its use on any concrete collection which implements that interface.
namespace System.Collections { public static class IListExtensions { public static string GetRowClass(this IList list, object item, string evenClass, string oddClass = "") { int index = list.IndexOf(item); return index % 2 == 0 ? evenClass : oddClass; } } }
To alternate row colours in your view it’s simply a case of calling the extension method and passing in the relevant classes for odd/even rows.
<table class="formattedTable" cellspacing="0"> <tr> <th>Name</th> <th>Business</th> <th>Email</th> </tr> <% foreach (var c in Model.Contacts) { %> <tr class="<%: Model.Contacts.GetRowClass(c, "evenRow", "oddRow") %>"> <td><%: c.Fullname %></td> <td><%: c.Business %></td> <td><%: c.Email)%></td> </tr> <% } %> </table>
I have put the extension method into the System.Collection namespace so that I only have to reference my extension method library in the project to access it, however if you are uncomfortable with this you can easily put it into your own namespace and import it manually.
Also, notice that I am using C# 4′s optional parameters on the oddClass parameter. A lot of times I only style one row and leave the other transparent so this allows for slightly neater view markup. If you aren’t using C# 4 you can simply overload the extension method.