In MVC3, how do you create alternating row colors on a @foreach list when using the Razor view engine?
@foreach (var item in Model) { <tr> <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> }
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With