0

Currently I used ternary expression following the post: Razor If/Else conditional operator syntax It works fine, but since in my case the expression values are pretty long I would like to write them in more clear manner, maybe using temporary variables on the way.

I know if as such is a statement, not expression, nevertheless how to write it? The outcome should be just string (for displaying on the page).

So starting from:

@(condition ? string1 : string2)

how its if counterpart would look like?

I searched and tried with writing ifs and lambdas as well, but every time I faced some syntax error. I would like to preserve this simplicity of returning string values, and not executing in each branch placing the value, like @Html.DisplayFor.

Update:

My string values are pure text, no html tags, or something fancy. Actual code just (a bit overcomplicated for this purpose, but I hope readable):

@(summary.Any() ? String.Join(", ", summary.Select(it => it.Key.ToString())) : "none")
astrowalker
  • 3,123
  • 3
  • 21
  • 40
  • declare a string. Then write the if and inside the if, assign the correct value to the string. Then at the end, output it. Standard C#, near enough. Show us what you tried please and what error you got. – ADyson Dec 16 '20 at 11:46

1 Answers1

2

I guess all you need are a couple of linebreaks

@if (someBoolean == true)
{
    <div>
        Boolean is true
    </div>
}
else
{
    <div>
        Boolean is false
    </div>
}

Or if you like to use a variable in the generated html:

@if (someBoolean == true)
{
    <div>
        Boolean is: @someBoolean
    </div>
}
else
{
    <div>
        Boolean is: @someBoolean
    </div>
}

Edit

In case you only want to have c# code in the if else, I believe it should look like this:

@if (someBoolean == true)
{
    @{
     // Your if instructions here
     }
}
else
{
    @{
     // Your else instructions here
     }
}
AdrAs
  • 676
  • 3
  • 14
  • Thank you. I tried to simplify such approach before but without success -- is it possible to drop div tags (I am looking at your first example)? – astrowalker Dec 16 '20 at 12:28
  • 1
    See edit above. Not sure if that works, I hope so – AdrAs Dec 16 '20 at 14:25
  • Thank you, but it does not. One thing is syntax, compilers does not like nested `@{ }` for branches, but the more problematic is the fact that `@if` is treated as statement, not an expression (just like regular C#). So for example using pure constant in one of the branches gives immediate error, because compiler expects assignments. – astrowalker Dec 17 '20 at 06:37