FernandoPaiva
FernandoPaiva

Reputation: 4460

How do I to change the style of a tag using Razor?

I have a HTML tag which I want to only be visible when a condition is true, otherwise it will be hidden. To do this, I'm trying to change the style attribute using Razor, but still can't do this.

Note that: I don't want to use JQuery, I want to use only Razor.

How could I do this ?

Trying

<!--it will only visible if the conditional true-->
<div class="form-group" @(usuario.role == RoleType.Investidor) ? style="display:none;" : style="display:normal;">
    <h1>Description</h1>
</div>

Upvotes: 1

Views: 3831

Answers (2)

NamiraJV
NamiraJV

Reputation: 666

You could try to do something like that:

@if (usuario.role != RoleType.Investidor)
{
    <div class="form-group" style="display: normal">
        <h1>Description</h1>
    </div>
}

If RoleType equals Investidor, the div will not be shown at all.

If presence of this element is important to you, you can leave it like that:

@if (usuario.role != RoleType.Investidor)
{
    <div class="form-group" style="display: normal">
        <h1>Description</h1>
    </div>
} else {
    <div class="form-group" style="display: none">
        <h1>Description</h1>
    </div>
}

Upvotes: 2

Tieson T.
Tieson T.

Reputation: 21191

I would assume something like this works:

<div class="form-group" style="@(usuario.role == RoleType.Investidor ? "display: none" : string.Empty)">
    <h1>Description</h1>
</div>

Move the ternary statement inside the attribute value for style. You may also be able to replace string.Empty with null - depending on context, that might enable the Razor engine to omit the attribute, rather than rendering an empty value.

Upvotes: 3

Related Questions