C# MVC3 Razor alternating items in a @foreach list?

Assuming you would rather not use CSS (i.e. :nth-child(odd)) you can either:

  • use a normal for loop:

    @for (int i = 0; i < Model.Count; i++)
    {
        ...
    }
    
  • use .Select:

    @foreach (var item in Model.Select((x, i) => new { Data = x, Index = i }))
    {
        ...
    }
    

Either way, you'd have access to the current index and could then use i % 2 == 1 as the condition for your background-color. Something like:

<tr style="background-color:@(i % 2 == 1 ? "red" : "white")">...</tr>

This is what CSS is for (changing style rather than content). Save the server the effort: Do it on the client.

Since you're using Razor, you can use JQuery. Here's how I do it in my projects:

$(document).ready(function () {
    $("table > tbody tr:odd").css("background-color", "#F7F7F7");
}

With ASP.NET MVC 3 and the new @helper syntax, there is a neater way to handle this.

First add this @helper method:

@helper AlternateBackground(string color) {
    if (ViewBag.count == null) { ViewBag.count = 0; }
    <text>style="background-color:@(ViewBag.count % 2 == 1 ? color : "none")"</text>
    ViewBag.count++;
}

Then just add the call to the helper in your <TR> element

@foreach (var item in Model) {    
    <tr @AlternateBackground("Red")>
        <td>@item.DisplayName</td>
        <td>@item.Currency</td>
        <td>@String.Format("{0:dd/MM/yyyy}", item.CreatedOn)</td>
        <td>@String.Format("{0:g}", item.CreatedBy)</td>
        <td>@Html.ActionLink("Edit", "Edit", new { id = item.Id })</td>
    </tr>
}

You could always do it in pure css using:

TABLE.test tr:nth-child(even)
{
    background-color: #EFEFEF;
}

How about something like this?

@for (int i = 0; i < Model.length; i++) {
  <tr @(i % 2 != 0 ? class="odd" : "")>
    <td>@Model[i].DisplayName</td>
    <td>@Model[i].Currency</td>
    <td>@String.Format("{0:dd/MM/yyyy}", Model[i].CreatedOn)</td>
    <td>@String.Format("{0:g}", Model[i].CreatedBy)</td>
    <td>@Html.ActionLink("Edit", "Edit", new { id = Model[i].Id })</td>
  </tr>