Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

asp.net mvc - 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>
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...