从 MVC 3 Razor View 变量中转义单引号
我在 item.Name 中有一个变量,其中包含字符串“It's Tuesday!”。 为了减少 JavaScript 错误,在 C# 控制器中我已经转义了这个单引号。 在网页上,它显示为“今天是星期二!”。
这至少可以防止任何 JavaScript 错误,但是,我不希望显示的实际字符串包含已转义的反斜杠。
一旦 javascript 错误已经得到处理,我怎样才能恢复转义?这感觉像是一个相当简单的问题,但我对 MVC 3 有点陌生。非常感谢任何提示!我的搜索没有找到任何具体的例子。
Razor 视图中的代码示例:
@foreach (var item in Model)
{
@Html.DisplayFor(modelItem => item.Name) // item.Name = "It\'s Tuesday!"
}
I have a variable within item.Name that contains the string "It's Tuesday!".
To alleviate javascript errors, in the c# controller I have already escaped this single quote.
On the webpage, it appears like this "It\'s Tuesday!".
This at least prevents any javascript errors, however, I do not want the actual string displayed to contain the backslash that has escaped it.
How might I be able to revert the escaping once the javascript errors have already been taken care of? This feels like a rather simple problem, but I am a bit unfamiliar with MVC 3. Any hint is much appreciated! My searching did not find me any example specific to this.
An example of my code in the Razor View:
@foreach (var item in Model)
{
@Html.DisplayFor(modelItem => item.Name) // item.Name = "It\'s Tuesday!"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建一个您可以使用的扩展方法或直接编码。我不会在视图获取它之前进行编码,除非您的视图模型中有一个单独的属性用于此目的(这不是一个坏主意()
这没有经过测试,但沿着这些思路
您可以调用 @Html.JavaScriptEncode(yourProperty)从视图或简单地引用您的编码属性名称。
Create an extension method you can use or simply encode directly. I would not encode prior to the view getting it unless you have a separate property in your viewmodel meant for this (not a bad idea()
This is not tested but something along these lines
You can then just call @Html.JavaScriptEncode(yourProperty) from the view or simply reference your encoded property name.
以下可用于防止再次对输出进行编码。然而,这确实取决于您自己正确处理它。
MVCHTMLString
The following can be used to prevent encoding of the output again. This does however rely on you properly dealing with it yourself.
MVCHTMLString
我更喜欢让我的观点变得愚蠢。因此,我有一个名为“Display”或“DisplayName”的属性,用于处理视图的转义。
I prefer to make my views dumb. Therefore, I'd have a property called something like 'Display' or 'DisplayName' which handled the escaping for the view.