How to write conditional within html element in blazor?

Viewed 676
@if (unit.unitNum != null)
 {
      <div>@unit.unitNum - @unit.type</div>
 }

Is there a way to right conditional within div element? I have to write conditional for unit.type too so it will be many ifs.

1 Answers

Yes you can write a conditional within a div element.

<div>
    @if(unit.unitNum != null)
    {
        @unit.unitNum - @unit.type
    }
    else {
        @* just do whatever you want here or don't write an else clause *@
    }
</div>

Note that you can also use String interpolation

<div>
    @if(unit.unitNum != null)
    {
        @($"{unit.unitNum} - {@unit.type}")
    }
</div>

You could even simplify this a bit more. Also since you didn't specify this, the type of unit.unitNum doesn't really matter here, e.g. it could be an int, or a string.

<div>
    @($"{(unit.unitNum != null ? unit.unitNum : "no number found")} - {@unit.type}")
</div>
Related