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>
}
An old post, but none of the answers covered this approach, so I will.
Since you are using MVC Razor utilizing the @helper function is the simplest, cleanest and best approach.
In the App_Code folder of your project add new item or modify your existing CustomeHelpers.cshtml file with the following code:
Then on your view your foreach loop would look like this:
You can pass a color identifier like "#ECEDEE" or the named color "Blue".
This way you only have to add the @Helper function once and it propagates throughout your application and it can be called on each view as needed by referencing the @CustomHelpers function.
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: