【问题标题】:Conditionally Display <th> tag in Razor在 Razor 中有条件地显示 <th> 标记
【发布时间】:2021-09-12 18:23:35
【问题描述】:

我的代码(enclosed in @for loop) 中有多行&lt;th&gt;&lt;td&gt; 标记,我想有条件地显示它们。其中一个&lt;th&gt; 标签如下所示:

@for (int j = 0; j < Model.Children.Count; j++)
{
 if (Model.Children[j].isCollapsible == true || Model.Children[j].IsCompany == true)
    {
<th class="..." style="width: 180px;">
    @Html.LabelForModel(Model.Children[j].Title)
    @if (Model.Children[j].isCollapsible == true && Model.Children[j].IsCompany == false)
                            {
                              // lines of code
                            }
</th>
 }
}

虽然这工作得很好,但是为了使代码更紧凑,我想用&lt;th&gt;标签的条件style=display:none属性替换上面代码sn-p中的外部if

我试过style="width: 180px; display: "@(Model.Children[j].isCollapsible == true || Model.Children[j].IsCompany == true)" ? none : table-cell",但它显示错误:

谁能告诉我我在这里做错了什么?

【问题讨论】:

    标签: c# html css asp.net-mvc razor


    【解决方案1】:

    用括号括起来三元,每个值都用引号引起来。

    display:@(Model.Children[j].isCollapsible || Model.Children[j].IsCompany ? "none" : "table-cell")
    

    这是一个精简的版本,可以很容易地看到引号应该在哪里。

    style="display:@(condition ? "" : "")"
    

    【讨论】:

    • 不,它不起作用,我仍然看到一个错误
    • 显示值周围有一组额外的引号。引号应该在每个值周围的括号内,而不是在整个语句周围(因为该语句已经包含在引号中)。
    • 是的,谢谢,错误确实发生了,但是当我看到输出时,条件似乎没有被应用。我附加了一个 !important 和 'none' 和 'table-cell'
    【解决方案2】:

    尝试删除display:之后的",然后在nonetable-cell之外添加""

    <th class="..." style="width: 180px;display:@(Model.Children[j].isCollapsible==true || Model.Children[j].IsCompany==true ? "none" : "table-cell")">
         ...
    </th>
    

    【讨论】:

      猜你喜欢
      • 2018-04-09
      • 2022-07-12
      • 1970-01-01
      • 2018-02-13
      • 2018-12-30
      • 2011-11-02
      • 2015-02-28
      • 1970-01-01
      • 2022-11-08
      相关资源
      最近更新 更多