Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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> } 
like image 498
JK. Avatar asked Feb 08 '11 04:02

JK.


2 Answers

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> 
like image 90
Kirk Woll Avatar answered Oct 19 '22 22:10

Kirk Woll


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"); } 
like image 21
trebormf Avatar answered Oct 19 '22 22:10

trebormf