MVC 视图更改指定行 bgcolor

Z.V*_*Z.V 0 asp.net-mvc if-statement html-table asp.net-mvc-views

在我的 MVC 视图中,我在表中显示来自我的模型的数据列表,如下所示。当一个字段满足我的 if-else 语句中的某些条件时,如何使指定的行改变颜色?似乎我不能为此在 if-else 中添加 jquery ......

我的看法:

    ...

    <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>
Run Code Online (Sandbox Code Playgroud)

Tim*_*Tim 5

您只需要在输出行的地方进行操作。一种方法是:

<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>
Run Code Online (Sandbox Code Playgroud)

有各种各样的方法来构建条件,只取决于你的场景。但关键是你可以在 foreach 循环中的任何地方访问 item 对象的 field3 属性,就像普通的 C# foreach