ForEach循环中的交替行颜色

时间:2014-05-08 00:00:48

标签: asp.net-mvc-4 razor foreach foreach-loop-container

我的foreach代码

请注意,我的第二行有不同的背景颜色。

@foreach (var item in Model.fNameList)
{
    <tr>
        <td style ="background-color:#E0EBEB; height:40px;width:100px;"><a href ="#" onclick='call();' style ="text-decoration:none; text-decoration-color:black;"> T-00001</a></td>
        <td style ="background-color:#E0EBEB; height:40px;width:200px;"> @item.firstName</td>
    </tr> 
    <tr>
        <td style ="background-color:#fff; height:40px;width:100px;"><a href ="#" onclick="call();" style ="text-decoration:none; text-decoration-color:black;"> T-00001</a></td>
        <td style ="background-color:#fff; height:40px;width:200px;"> @item.firstName</td>
    </tr>
}

我希望我的第二个 TR 标记具有我的第二个值&#34; FIRSTNAME&#34;,例如:如果 var item [0] &#34; FIRSTNAME&#34; =&#34; GEM&#34; var item [1] &#34; FIRSTNAME&#34; =&#34; DIAMOND&#34; 。现在如果我运行我的代码,我的第一个 TR 标签的值有&#34; FIRSTNAME&#34; =&#34; GEM&#34; ,而在第二个 TR 标记中,值为&#34; FIRSTNAME&#34; =&#34; GEM&#34; 。现在我希望我的第二个 TR 标记具有以下值:&#34; FIRSTNAME&#34; =&#34; DIAMOND&#34;

1 个答案:

答案 0 :(得分:3)

修改 好的,我现在更了解你的问题,你想要做交替的行颜色。最好的方法是设置一个变量,让你知道你是否交替。我已经更新了我的例子来展示这一点。

然后,在foreach循环中只需要一组<tr>。每个项目只输出一个<tr>

@{
    var altRow = false;
    foreach (var item in Model.fNameList)
    {
        <tr>
            <td style ="background-color:@(altRow ? "#fff" : "#E0EBEB"); height:40px;width:100px;"><a href ="#" onclick='call();' style ="text-decoration:none; text-decoration-color:black;"> T-00001</a></td>
            <td style ="background-color:@(altRow ? "#fff" : "#E0EBEB"); height:40px;width:200px;"> @item.firstName</td>
        </tr>
        altRow = !altRow; 
    }
}

这样做是通过foreach循环在每次迭代时将altRow变量从true切换为false。如果为true,则将背景颜色设置为#fff,如果为false,则设置为#E0EBEB

所以 - 如果我们使用以下数据来浏览此代码:

item[0].FirstName = "Gem"
item[1].FirstName = "Diamond"

然后预期输出

    <tr>
        <td style ="background-color:#E0EBEB; height:40px;width:100px;"><a href ="#" onclick='call();' style ="text-decoration:none; text-decoration-color:black;"> T-00001</a></td>
        <td style ="background-color:#E0EBEB; height:40px;width:200px;">Gem</td>
    </tr> 
    <tr>
        <td style ="background-color:#fff; height:40px;width:100px;"><a href ="#" onclick='call();' style ="text-decoration:none; text-decoration-color:black;"> T-00001</a></td>
        <td style ="background-color:#fff; height:40px;width:200px;">Diamond</td>
    </tr>