I have the following razor code with ternary operator to include or omit a data-* attribute:
<select class="form-control"
@(field.DependentDropdown ? $"data-selected={Model.KeyValues.GetValue(field.Name)}" : "")>
When it renders in HTML it comes out like this:
<select class="form-control"
data-selected="Toyota" yaris="">
As you can see the value for the data-selected attribute is not being correctly formatted - it should be one word enclosed in double quotes "Toyota Yaris"
.
How do I correctly escape or add doubles quotes to:
$"data-selected={Model.KeyValues.GetValue(field.Name)}"
What you need is to use the seldom seen <text>
syntax
e.g.
<h1 @{if (true) { <text>data-selected="Hello world"</text> } }>Hello</h1>
try this:
<select class="form-control"
@{ if (field.DependentDropdown) { <text>data-selected="@Model.KeyValues.GetValue(field.Name)"</text> } }>
I'm having a tough time convincing it to work in the ternary operator - feel free to edit answer if you get the syntax right
Wrap the string in a call to the Raw() method on the HtmlHelper class.
<select class="form-control"
@(field.DependentDropdown ? Html.Raw($"data-selected=\"{Model.KeyValues.GetValue(field.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