简体   繁体   中英

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

What you need is to use the seldom seen <text> syntax

eg

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

You can try this.

An example in Fiddle

 $"data-selected=\"{Model.KeyValues.GetValue(field.Name)}\""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM