JK.*_*JK. 46 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>
}
Run Code Online (Sandbox Code Playgroud)
Kir*_*oll 56
假设您不想使用CSS(即:nth-child(odd)),您可以:
使用正常for循环:
@for (int i = 0; i < Model.Count; i++)
{
...
}
Run Code Online (Sandbox Code Playgroud)用途.Select:
@foreach (var item in Model.Select((x, i) => new { Data = x, Index = i }))
{
...
}
Run Code Online (Sandbox Code Playgroud)无论哪种方式,您都可以访问当前索引,然后可以i % 2 == 1将其用作背景颜色的条件.就像是:
<tr style="background-color:@(i % 2 == 1 ? "red" : "white")">...</tr>
Run Code Online (Sandbox Code Playgroud)
tre*_*rmf 42
这就是CSS的用途(改变风格而不是内容).节省服务器的努力:在客户端上执行.
由于您使用的是Razor,因此可以使用JQuery.以下是我在项目中的表现:
$(document).ready(function () {
$("table > tbody tr:odd").css("background-color", "#F7F7F7");
}
Run Code Online (Sandbox Code Playgroud)
Ken*_*isa 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++;
}
Run Code Online (Sandbox Code Playgroud)
然后只需将调用添加到<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>
}
Run Code Online (Sandbox Code Playgroud)
the*_*tus 22
您总是可以使用以下方法在纯CSS中执行以下操作:
TABLE.test tr:nth-child(even)
{
background-color: #EFEFEF;
}
Run Code Online (Sandbox Code Playgroud)
这样的事怎么样?
@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>
Run Code Online (Sandbox Code Playgroud)
@{
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++;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
97676 次 |
| 最近记录: |