Using a ternary operator to output a string containing spaces in Razor

I am trying to use a ternary operator in Razor similar to this question , but what I want to infer contains spaces. 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 useless. I tried a bunch of different combinations of escaped quotes, @ characters and @ characters, 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" 

Does anyone know how this should be done?

+6
source share
2 answers

The value attribute does not have its own quotation marks, so they are automatically added in front of the space. Try moving the value outside the expression.

 value="@(selectedGoal == null ? "" : selectedGoal.Name)" 
+9
source

What about

 @(selectedGoal == null ? "" : "value=\"" + selectedGoal.Name + \") 

Or you can try to execute them directly as an HTML block using my Html literal method in a Razor thermal expression

0
source

Source: https://habr.com/ru/post/915917/


All Articles