javascript 从 MVC 3 Razor View 变量中转义单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8479260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escaping single quote from an MVC 3 Razor View variable
提问by mherr
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!".
我在 item.Name 中有一个变量,其中包含字符串“It's Tuesday!”。为了减少 javascript 错误,在 c# 控制器中我已经转义了这个单引号。在网页上,它看起来像这样“今天是星期二!”。
This at least prevents any javascript errors, however, I do not want the actual string displayed to contain the backslash that has escaped it.
这至少可以防止任何 javascript 错误,但是,我不希望显示的实际字符串包含已转义的反斜杠。
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.
一旦 javascript 错误已经得到处理,我如何能够恢复转义?这感觉是一个相当简单的问题,但我对 MVC 3 有点陌生。非常感谢任何提示!我的搜索没有找到任何特定于此的示例。
An example of my code in the Razor View:
我在 Razor 视图中的代码示例:
@foreach (var item in Model)
{
@Html.DisplayFor(modelItem => item.Name) // item.Name = "It\'s Tuesday!"
}
回答by Adam Tuliper - MSFT
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
这不是经过测试的,而是沿着这些方向的
public static class HtmlExtensions
{
public static IHtmlString JavaScriptEncode(this HtmlHelper html, string item)
{
return new HtmlString(HttpUtility.JavaScriptStringEncode(item));
}
}
You can then just call @Html.JavaScriptEncode(yourProperty) from the view or simply reference your encoded property name.
然后,您可以从视图中调用 @Html.JavaScriptEncode(yourProperty) 或简单地引用您的编码属性名称。
回答by RubbleFord
The following can be used to prevent encoding of the output again. This does however rely on you properly dealing with it yourself.
以下内容可用于防止再次对输出进行编码。然而,这确实依赖于您自己正确处理它。
@MvcHtmlString.Create(yourString)
回答by Jeff Sheldon
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.
我更愿意让我的观点变得愚蠢。因此,我有一个名为“Display”或“DisplayName”之类的属性,用于处理视图的转义。