C#MVC3 Razor在@foreach列表中交替项目?

时间:2011-02-08 04:27:30

标签: c# asp.net-mvc razor

在MVC3中,如何在使用Razor视图引擎时在@foreach列表上创建交替的行颜色?

@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 个答案:

答案 0 :(得分:55)

假设您不想使用CSS(即:nth-child(odd)),您可以:

  • 使用普通for循环:

    @for (int i = 0; i < Model.Count; i++)
    {
        ...
    }
    
  • 使用.Select

    @foreach (var item in Model.Select((x, i) => new { Data = x, Index = i }))
    {
        ...
    }
    

无论哪种方式,您都可以访问当前索引,然后可以使用i % 2 == 1作为背景颜色的条件。类似的东西:

<tr style="background-color:@(i % 2 == 1 ? "red" : "white")">...</tr>

答案 1 :(得分:42)

这就是CSS的用途(改变风格而不是内容)。节省服务器的努力:在客户端上进行。

由于您使用的是Razor,因此您可以使用JQuery。以下是我在项目中的表现:

$(document).ready(function () {
    $("table > tbody tr:odd").css("background-color", "#F7F7F7");
}

答案 2 :(得分:26)

使用ASP.NET MVC 3和新的@helper语法,有一种更简洁的方法来处理它。

首先添加这个@helper方法:

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

然后只需将调用添加到<TR>元素

中的帮助程序中
@foreach (var item in Model) {    
    <tr @AlternateBackground("Red")>
        <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>
}

答案 3 :(得分:22)

你总是可以使用以下方法在纯CSS中完成:

TABLE.test tr:nth-child(even)
{
    background-color: #EFEFEF;
}

答案 4 :(得分:9)

这样的事情怎么样?

@for (int i = 0; i < Model.length; i++) {
  <tr @(i % 2 != 0 ? class="odd" : "")>
    <td>@Model[i].DisplayName</td>
    <td>@Model[i].Currency</td>
    <td>@String.Format("{0:dd/MM/yyyy}", Model[i].CreatedOn)</td>
    <td>@String.Format("{0:g}", Model[i].CreatedBy)</td>
    <td>@Html.ActionLink("Edit", "Edit", new { id = Model[i].Id })</td>
  </tr>

答案 5 :(得分:5)

@{  
    int i = 0;
    foreach (Account acct in Model)
    {
        <div class="row @(i%2==0?"even":"odd")">     
            <a href="/Account/Details/@acct.id">@acct.name</a>
        </div>
        i++;
    }
}

答案 6 :(得分:3)

原文:http://15daysofjquery.com/table-striping-made-easy/5/ 作者:杰克博恩 jQuery Zebra_Striping_Made_Easy

=============== Java脚本===================

$(document).ready(function () {
          $('.stripeMe tr:even').addClass('alt');

          $('.stripeMe tr').hover(
            function () {
                $(this).addClass("highlight");
              },
             function () {
                $(this).removeClass("highlight");
              });
      });

================= css =================

tr.alt td {
background-color : #F7F7F7;
}
tr.highlight td {
background-color : #bcd4ec;
}

=============== HTML ===============

<table class="stripeMe">

答案 7 :(得分:2)

关于它的文档不多,但Loop Helper(http://nuget.org/Packages/Packages/Details/Loop-Helper-for-WebMatrix-0-1)为您提供了检测Even / Odd / etc的支持。项目

答案 8 :(得分:1)

一篇旧帖子,但没有一个答案涵盖了这种方法,所以我会。

由于您正在使用MVC Razor,因此使用@helper函数是最简单,最干净和最好的方法。

在项目的App_Code文件夹中添加新项目或使用以下代码修改现有的CustomeHelpers.cshtml文件:

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

然后在您的视图中,您的foreach循环将如下所示:

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

您可以传递一个颜色标识符,例如&#34;#ECEDEE&#34;或者命名的颜色&#34;蓝色&#34;。

这样你只需要添加一次@Helper函数,它就会在整个应用程序中传播,并且可以根据需要通过引用@CustomHelpers函数在每个视图上调用它。

答案 9 :(得分:0)

使用jQuery DataTable插件怎么样?我在我开发的MVC2应用程序中使用它。

http://www.datatables.net/

答案 10 :(得分:0)

我用来支持IE8(企业浏览器,而不是选择)的解决方案是将the_lotus的解决方案与jquery solution

结合起来

由于IE8不支持nth-child()使用此css

.tableclass tr.even{
    background:#E6EDF5;
}

使用jQuery执行此操作:

$(document).ready(function() {
    $(".table tr:nth-child(even)").addClass("even");
});

答案 11 :(得分:0)

可以让框架决定如何最好地渲染它,大概是使用一些浏览器检测逻辑和内置的其他任何好处,如下所示,并继续你的寿命。

: - )

我的观点是,使用这种方法,WebGrid将使用最佳技术控制交替的网格颜色(至少它是设计至少使用),用于检测到的浏览器。它可能不会使用“第n”CSS语法,但无论如何,这可能不适用于所有目标受众,因此您必须自己检测浏览器并发出不同的内容。当然,现在每个人都应该使用符合CSS 3.x标准的浏览器,但里程会有所不同。

@myWebGrid.GetHtml
    (
    tableStyle: "some-style",
    headerStyle: "some-head-style",
    alternatingRowStyle: "some-fancy-alt-row-style",
    etc ...
    )

System.Web.Helpers.WebGrid的{​​{1}}方法签名如下所示:

GetHtml

答案 12 :(得分:0)

您可以做的是在odd

之外设置变量foreach()
@{
    var odd = false;
}

然后,在foreach循环中,您将更改它的值,然后在if条件下使用它来设置交替类。

@foreach (var item in Model) {
    odd = !odd;

    <tr class="@(odd ? "odd" : "even")">
        <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>
}

答案 13 :(得分:0)

@helper Prop(List prop) {     foreach(支柱中的var p)     {     p     } }

格式:@Prop(@ item.Prop)