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

6
  • 1
    There is not enough information here - as it stands it seems all you need is another condition in your existing if. Or maybe you just want to use the ? operator - @unit?.unitNum - @unit?.type ? It's hard to know what you are asking for. Commented May 31, 2021 at 23:10
  • You haven't described what you want well enough for anyone to answer your question. Commented Jun 1, 2021 at 1:06
  • @unit?.unitNum - @unit?.type This is a good idea but how can I have else{} if unit.unitNum and unit.type were null? Commented Jun 1, 2021 at 9:42
  • Can structs can be null or is it a string?? or do you mean default? unit? is testing for (unit is null) Commented Jun 1, 2021 at 9:44
  • If I make the question clearer I can say that I want to remove @if (unit.unitNum != null){} and but I want to have conditional like this: @unit?.unitNum - @unit?.type as Magoo has mentioned above. now how can I have else {} within div element? Commented Jun 1, 2021 at 9:45

1 Answer 1

6

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>
Sign up to request clarification or add additional context in comments.

1 Comment

great pleasure to help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.