Search code examples
asp.netasp.net-mvcrazor

asp.net mvc - Simplest way to provide alternate row styling in Razor


Given the following Razor code:

<tbody>
    @foreach (Profession profession in Model)
    {
        <tr>
            <td>@profession.Name</td>
            <td>@profession.PluralName</td>
            <td>@Html.ActionLink("Edit", "AddOrEdit", new { Id = profession.ProfessionID })</td>
        </tr>
    }
</tbody>

What's the simplest way to provide some kind of alternate row styling? (i.e. different styling for odd and even rows.)

I don't seem to be able to add arbitrary C# to declare a bool variable which gets flipped each iteration of the foreach loop in order to set a classname for the tr, for example.


Solution

  • I'd recommend doing this in straight CSS (see here for more details):

    tr:nth-child(odd)    { background-color:#eee; }
    tr:nth-child(even)   { background-color:#fff; }