C# MVC3 Razor alternating items in a @foreach list

2019-01-21 03:23发布

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>
}

14条回答
何必那么认真
2楼-- · 2019-01-21 03:59

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:

@helper AlternateBackground(string color, Int32 iViewBagCount) {
    if (iViewBagCount == null) { iViewBagCount = 0; }
    <text>style="background-color:@(iViewBagCount % 2 == 1 ? color : "none")"</text>
    iViewBagCount++;
}

Then on your view your foreach loop would look like this:

@foreach (var item in Model) {    
    <tr @CustomHelpers.AlternateBackground("#ECEDEE", Model.Count())>
        <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>
}

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.

查看更多
Summer. ? 凉城
3楼-- · 2019-01-21 04:03

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");
}
查看更多
登录 后发表回答