Search code examples
c#razorinterpolationstring-interpolation

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

Solution

  • 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