C# 在 Razor 中使用字符串插值转义双引号?

ada*_*m78 7 c# interpolation string-interpolation razor

我有以下带有三元运算符的剃刀代码来包含或省略 data-* 属性:

 <select class="form-control"
        @(field.DependentDropdown ? $"data-selected={Model.KeyValues.GetValue(field.Name)}" : "")>
Run Code Online (Sandbox Code Playgroud)

当它在 HTML 中呈现时,它是这样的:

<select class="form-control" 
        data-selected="Toyota" yaris="">
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,数据选择属性的值的格式不正确——它应该是用双引号括起来的一个词"Toyota Yaris"

如何正确转义或添加双引号:

 $"data-selected={Model.KeyValues.GetValue(field.Name)}"
Run Code Online (Sandbox Code Playgroud)

Zep*_*eph 8

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

e.g.

<h1 @{if (true) { <text>data-selected="Hello world"</text> } }>Hello</h1>
Run Code Online (Sandbox Code Playgroud)

try this:

 <select class="form-control"
        @{ if (field.DependentDropdown) { <text>data-selected="@Model.KeyValues.GetValue(field.Name)"</text> } }>
Run Code Online (Sandbox Code Playgroud)

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


小智 5

将字符串包装在对 HtmlHelper上的 Raw() 方法的调用中。

<select class="form-control"
    @(field.DependentDropdown ? Html.Raw($"data-selected=\"{Model.KeyValues.GetValue(field.Name)}\"") : "")>
Run Code Online (Sandbox Code Playgroud)