I'm trying to use a ternary operator in Razor, similar to this question, but what I want to output contains whitespace. This code
@(selectedGoal == null ? "" : "value=" + selectedGoal.Name)
should produce
value="Goal 3"
as the value of selectedGoal.Name is "Goal 3". Instead, I get
value="Goal" 3
which is no good. I've tried a bunch of different combinations of escaped quotes, @ symbols and no @ symbols, and I just can't get this to work, i.e.
@(selectedGoal == null ? "" : "value=" + "selectedGoal.Name")
@(selectedGoal == null ? "" : "[email protected]")
and then I just get something like
value="selectedGoal.Name"
Anyone know how this should be done?
Ternary operator values The values part of the ternary operator in the above example is this: “This is an even number!” : “This is an odd number!”; In the example above, if the condition evaluates to true then the ternary operator will return the string value “This is an even number!”.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Here's a simple decision-making example using if and else: int a = 10, b = 20, c; if (a < b) { c = a; } else { c = b; } printf("%d", c); This example takes more than 10 lines, but that isn't necessary. You can write the above program in just 3 lines of code using a ternary operator.
Example: C Ternary Operator Here, age >= 18 - test condition that checks if input value is greater or equal to 18. printf("You can vote") - expression1 that is executed if condition is true. printf("You cannot vote") - expression2 that is executed if condition is false.
Your value attribute is missing its own quotes, so they are being automatically added before the space. Try moving value
outside of the expression.
value="@(selectedGoal == null ? "" : selectedGoal.Name)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With