[英]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:我有以下带有三元运算符的剃刀代码来包含或省略 data-* 属性:
<select class="form-control"
@(field.DependentDropdown ? $"data-selected={Model.KeyValues.GetValue(field.Name)}" : "")>
When it renders in HTML it comes out like this:当它在 HTML 中呈现时,它是这样的:
<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"
.如您所见,数据选择属性的值格式不正确 - 它应该是一个用双引号括起来的单词"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你需要的是使用很少见的<text>
语法
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.将字符串包装在对 HtmlHelper类上的 Raw() 方法的调用中。
<select class="form-control"
@(field.DependentDropdown ? Html.Raw($"data-selected=\"{Model.KeyValues.GetValue(field.Name)}\"") : "")>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.