如何在C# MVC3 Razor中使用@foreach列表交替显示项目?

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

2
一年过去了,由于有如此多的浏览量,我不得不更改接受的答案。CSS是正确的方法,而不是代码。 - JK.
6
@trebormf的回答依赖于JavaScript。得票最高的答案(@Kirk Woll)将可以完成相同的任务,但不需要依赖JavaScript,这样可以兼容更多客户端,更轻量级和更快速的渲染 - 在我看来是“更正确”的。最初选择的答案确实使用了CSS。它是嵌入式CSS,但无论如何,还是使用了CSS。您可以将其更改为设置类名或其他方式,而不是嵌入式CSS。 - BenSwayne
2
CSS是应用样式的正确方式。然而,使用JQuery在DOM中呈现表格,然后进行更改仍然是代码:只不过不是你的代码。我怀疑如果您对页面生成进行性能计时,您会发现基于服务器的方法更快,并且不依赖JS。 - Quango
14个回答

0

我使用的一种解决方案来支持IE8(企业浏览器,而不是选择)是将the_lotus的解决方案与{{link1:jquery解决方案}}相结合。

由于IE8不支持nth-child(),因此请使用此CSS。

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

使用jQuery来实现:

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

0

你可以让框架决定如何最好地呈现它,大概使用一些浏览器检测逻辑和内置的其他功能,类似于以下内容,然后继续你的生活。

:-)

我的意思是,通过这种方法,WebGrid将使用最佳技术(至少是其设计要使用的最佳技术)控制交替的网格颜色,以适应检测到的浏览器。 它可能不会使用“nth” CSS语法,但这对您预期的所有受众可能都不起作用,所以您必须自行检测浏览器并发出不同的内容。 当然,现在每个人都应该使用符合CSS 3.x标准的浏览器,但效果因人而异。

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

System.Web.Helpers.WebGridGetHtml方法签名如下:

public IHtmlString GetHtml
    (
    string tableStyle = null,
    string headerStyle = null,
    string footerStyle = null,
    string rowStyle = null,
    string alternatingRowStyle = null,
    string selectedRowStyle = null,
    string caption = null,
    bool displayHeader = true,
    bool fillEmptyRows = false,
    string emptyRowCellValue = null,
    IEnumerable<WebGridColumn> columns = null,
    IEnumerable<string> exclusions = null,
    WebGridPagerModes mode = WebGridPagerModes.Numeric | WebGridPagerModes.NextPrevious,
    string firstText = null,
    string previousText = null,
    string nextText = null,
    string lastText = null,
    int numericLinksCount = 5,
    object htmlAttributes = null
    );

0

0

@helper Prop(List prop) { foreach (var p in prop) { p } }

格式:@Prop(@item.Prop)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接