Using ternary operator to output a string containing whitespace in Razor

asp.net, razor, ternary-operator

Solution

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)"

Problem

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 ? "" : "value=@selectedGoal.Name") ``` and then I just get something like ``` value="selectedGoal.Name" ``` Anyone know how this should be done?

Original source

Related problems