-2

我的 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标签具有我的“FIRSTNAME”的第二个值,例如:如果var item[0]"FIRSTNAME" = "GEM",并且var item[1]"FIRSTNAME" = "DIAMOND"。现在,如果我运行我的代码,我的第一个TR标签的值是“FIRSTNAME”= “GEM”,而在第二个TR标签中,值也是“FIRSTNAME”=“GEM”。现在我希望我的第二个TR标签具有值:"FIRSTNAME" = "DIAMOND"

4

1 回答 1

3

编辑 好的,我现在更了解您的问题,您想要交替行颜色。最好的方法是设置一个变量,让你知道你是否在交替。我已经更新了我的示例以显示这一点。

然后,你只需要<tr>在你的 foreach 循环中设置一组。每个项目都将输出一个<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。当为真时,它将背景颜色设置为#fff,当为假时,#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> 
于 2014-05-08T00:03:44.807 回答