Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write conditional within html element in blazor?

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

like image 546
mohandes Avatar asked Nov 16 '25 02:11

mohandes


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>
like image 99
LuckyLikey Avatar answered Nov 17 '25 22:11

LuckyLikey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!