【问题标题】:Select class using switch-case statement in Razor view在 Razor 视图中使用 switch-case 语句选择类
【发布时间】:2019-07-19 11:27:40
【问题描述】:

我想根据WhichColor 属性的值更改类名。如果为 1,则应为红色,如果为 2,则为蓝色,依此类推。我知道如何使用:? 语句对两种颜色执行此操作。但是如果我有更多呢?

我试过用 switch case 来做,但它不允许我返回字符串我可能不明白 switch case 在这种情况下是如何工作的。

<td class="@{
        switch (item.WhichColor)
        {
            case 1:
                return "red";
            case 2:
                return "blue";
            case 3:
                return "green";
            default:
                break;
        }
            } ">
        @Html.DisplayFor(modelItem => item.WhichColor)
    </td>

我希望它像上面的 switch-case 一样工作,但它不允许我返回字符串。我怎样才能做到这一点?

【问题讨论】:

    标签: css razor model-view-controller


    【解决方案1】:

    好的,我已经设法通过合并的十进制语句来做到这一点:

    <td class="@(
            (item.WhichColor == 1) ? "green" : (item.WhichColor == 2) ? "yellow" : (item.WhichColor == 3) ? "red" : (item.WhichColor == 4) ? "blue" : (item.WhichColor == 5 ? "gray" : "")
                )">
            @Html.DisplayFor(modelItem => item.WhichColor)
        </td>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 2013-09-24
      相关资源
      最近更新 更多