9

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?

5
  • Nothing you are showing would produce those results. Clearly, the problem is in whatever sets the value of selectedGoal.Name. Commented May 16, 2012 at 15:51
  • I use selectedGoal.Name elsewhere in the page and it works fine, no misplaced quotes or anything. Commented May 16, 2012 at 16:00
  • Something is placing those quotes, and the code you have shown is not doing it. Commented May 16, 2012 at 16:18
  • See stackoverflow.com/questions/3800473/… Commented Nov 11, 2013 at 23:24
  • Does this answer your question? How to use ternary operator in razor (specifically on HTML attributes)? Commented Aug 17, 2021 at 2:24

2 Answers 2

14

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)"
Sign up to request clarification or add additional context in comments.

7 Comments

Comes out like this: value=""Goal" 2".
@wohanley, I'm not sure where those extra sets of quotes would come from. Does .Name actually contain the quotes as part of the string?
It really, really shouldn't, but if this Razor is correct then maybe that's the only possibility. I'll triple-check.
There should be nowhere that quotes are added to Name, and it's working fine (that is, quote-free) in other places on the same page.
@wohanley, you're right try the updated answer. I think @ is encoding the quotes again. My previous answer wrapped with @Html.Raw instead of just @ seems to work, but this way is a little cleaner anyways.
|
-1

What about

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

Or you can try rendering them directly as an HTML block, using my method on Html literal in Razor ternary expression

1 Comment

It will escape the HTML encode the quotes, so this won't work. Did you just guess?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.