在 Razor 中以正确的方式使用 C# 6 字符串插值
Using C# 6 String interpolation in Razor the Correct Way
示例:
<button data-value="$'{@item.CustomerID}_{@item.CustomerType}'"></button>
结果:
$'{34645}_{71}'
预期:
34645_71
更新:
必须启用 C#6 并安装适当的包,@smdrager 的最后两种技术才能起作用。在VS2015>>点击项目菜单>>点击启用6#
在您提供的示例中,字符串插值不是必需的。使用标准的剃刀语法,你可以得到你想要的结果:
<button data-value="@(item.CustomerID)_@item.CustomerType"></button>
哪个会产生<button data-value="34567_123"></button>
与插值等价的是:
@Html.Raw($"<button data-value='{item.CustomerID}_{item.CustomerType}'></button>")
但是你失去了 HTML 编码以防止脚本注入(尽管这对于你正在处理的数据类型来说似乎不太可能)。
编辑:
如果您想变得完全古怪,可以将两者混合使用。
<button data-value="@($"{item.CustomerID}_{item.CustomerType}")"></button>
但那更冗长且难以阅读。
示例:
<button data-value="$'{@item.CustomerID}_{@item.CustomerType}'"></button>
结果:
$'{34645}_{71}'
预期:
34645_71
更新: 必须启用 C#6 并安装适当的包,@smdrager 的最后两种技术才能起作用。在VS2015>>点击项目菜单>>点击启用6#
在您提供的示例中,字符串插值不是必需的。使用标准的剃刀语法,你可以得到你想要的结果:
<button data-value="@(item.CustomerID)_@item.CustomerType"></button>
哪个会产生<button data-value="34567_123"></button>
与插值等价的是:
@Html.Raw($"<button data-value='{item.CustomerID}_{item.CustomerType}'></button>")
但是你失去了 HTML 编码以防止脚本注入(尽管这对于你正在处理的数据类型来说似乎不太可能)。
编辑:
如果您想变得完全古怪,可以将两者混合使用。
<button data-value="@($"{item.CustomerID}_{item.CustomerType}")"></button>
但那更冗长且难以阅读。