使用单引号将字符串从 MVC Razor 传递到 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5749590/
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
Passing strings with Single Qoute from MVC Razor to JavaScript
提问by user646306
This seems so simple it's embarrassing. However, the first question is when passing a value from the new ViewBag in MVC 3.0 (Razor) into a JavaScript block, is this the correct way to do it? And more importantly, where and how do you apply the proper string replacement code to prevent a single quote from becoming ' as in the resultant alert below?
这看起来很简单,很尴尬。但是,第一个问题是,将值从 MVC 3.0 (Razor) 中的新 ViewBag 传递到 JavaScript 块时,这是正确的方法吗?更重要的是,您在哪里以及如何应用正确的字符串替换代码来防止单引号变成 ' ,如下面的结果警报所示?
Adding this into a single script block:
将此添加到单个脚本块中:
alert('@ViewBag.str') // "Hi, how's it going?"
Results in the following alert:
导致以下警报:
回答by ataddeini
Razor will HTML encode everything, so to prevent the ' from being encoded to '
, you can use
Razor 将对所有内容进行 HTML 编码,因此为了防止 ' 被编码为'
,您可以使用
alert('@Html.Raw(ViewBag.str)');
However, now you've got an actual ' in the middle of your string which causes a javascript error. To get around this, you can either wrap the alert string in double quotes (instead of single quotes), or escape the ' character. So, in your controller you would have
但是,现在您的字符串中间有一个实际的 ' ,这会导致 javascript 错误。为了解决这个问题,您可以将警报字符串用双引号(而不是单引号)括起来,或者转义 ' 字符。所以,在你的控制器中,你会有
ViewBag.str = "Hi, how\'s it going?";