Question

My foreach code

Notice that my second row has a different background color.

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

I want my second TR tag to have the second value of my "FIRSTNAME", example: if var item[0] is "FIRSTNAME" = "GEM", and var item[1] is "FIRSTNAME" = "DIAMOND". now if I run my code, the value of my first TR tag has "FIRSTNAME" = "GEM" while in the second TR tag the value is "FIRSTNAME" = "GEM" as well. Now I want my second TR tag to have the value: "FIRSTNAME" = "DIAMOND".

Was it helpful?

Solution

EDIT Ok, I understand your issue more now, you are wanting to do alternating row colors. The best way to do that is to set a variable that allows you to know if you are alternating or not. I have updated my example to show this.

Then, you only need one set of <tr> in your foreach loop then. Each item will output exactly one <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; 
    }
}

What this does is switches the altRow variable from true to false on each iteration through the foreach loop. When true, it will set the background color to #fff and when false, #E0EBEB

So - if we walk through this code with the following data:

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

Then the expected output will be

    <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> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top