Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ternary operator to output a string containing whitespace in Razor

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?

like image 752
wohanley Avatar asked May 16 '12 15:05

wohanley


People also ask

Can ternary operator return string?

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!”.

How do you handle 3 conditions in a ternary operator?

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.

Can we use ternary operator in printf?

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.

What is ternary operator example?

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.


1 Answers

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)"
like image 138
Brandon Avatar answered Oct 13 '22 05:10

Brandon