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>
}
What you can do is to set a variable
odd
outside of theforeach()
And then, inside your foreach loop, you'd change the value of it and then use it in an
if
condition to set the alternating classes.@helper Prop(List prop) { foreach (var p in prop) { p } }
format: @Prop(@item.Prop)
Assuming you would rather not use CSS (i.e.
:nth-child(odd)
) you can either:use a normal for loop:
use
.Select
: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:You could always do it in pure css using:
There isn't much documentation on it, but the Loop Helper (http://nuget.org/Packages/Packages/Details/Loop-Helper-for-WebMatrix-0-1) gives you support for detecting Even/Odd/etc. items.
You could let the framework decide how best to render it, presumably using a bit of browser detection logic and whatever other goodness it has built-in, something like the following, and get on with your life.
:-)
My point being that with this approach the WebGrid will control the alternating grid colors using the best technology it can (best that it is designed to use, at least) for the detected browser. It might not use "nth" CSS syntax, but that might not work for all of your intended audience, anyway, so you'd have to detect the browser and emit different content on your own. Of course everybody should be using a CSS 3.x-compliant browser by now, but mileage varies.
The
System.Web.Helpers.WebGrid
'sGetHtml
method signature looks like this here: