MVC View change specified row bgcolor

3.9k views Asked by At

In my MVC view, I am displaying list of data from my model in a table as shown below. How to make a specified row to change color when one of the field satisfy certain condition within my if-else statement? It does not seems like I can add a jquery inside my if-else there for the purpose...

My View:

    ...

    <table>

    ...      

    @foreach (var item in Model) {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.field1)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.field2)
                </td>
                <td>
                    @if(item.field3== 0){
                        //change this row to grey color
                }
                else {
                        @Html.DisplayFor(modelItem => item.field3)
                }
                </td>

      ....

     </table>
1

There are 1 answers

0
Tim On BEST ANSWER

You just need to do it up where you are outputting the row. One way would be:

<table>

    ...      

    @foreach (var item in Model) {
            <tr style='background-color: @(item.field3 == 0 ? "gray" : "white");'>
                <td>
                    @Html.DisplayFor(modelItem => item.field1)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.field2)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.field3)
                </td>
      }
      ....

     </table>

There are all sorts of ways to construct that conditional, just depends on your scenario. But the key is that you can access the field3 property of the item object anywhere in that foreach loop, just like a normal C# foreach