Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Escaping double quotes with String interpolation in Razor?

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)}"
like image 914
adam78 Avatar asked Sep 14 '18 15:09

adam78


2 Answers

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

like image 145
Zeph Avatar answered Nov 07 '22 16:11

Zeph


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)}\"") : "")>
like image 33
cneale Avatar answered Nov 07 '22 16:11

cneale