Search code examples
c#htmlcssasp.net-mvcrazor

Conditionally Display <th> tag in Razor


There are multiple rows of <th> & <td> tags in my code(enclosed in @for loop) which I want to display conditionally. One of such <th> tags looks like this:

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

Although this works perfectly fine, but in order to make the code more compact, I want to replace the outer if in the above code snippet with a conditional style=display:none property for the <th> tag

I have tried style="width: 180px; display: "@(Model.Children[j].isCollapsible == true || Model.Children[j].IsCompany == true)" ? none : table-cell" but it shows an error:

enter image description here

Can someone please tell me what I'm doing wrong here?


Solution

  • Enclose the ternary with parentheses, with quotes around each value.

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

    Here is a stripped version which makes it easy to see where the quotes should be.

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