使用 Single Qoute 将字符串从 MVC Razor 传递到 JavaScript
这看起来很简单,却很尴尬。然而,第一个问题是,当将 MVC 3.0 (Razor) 中的新 ViewBag 中的值传递到 JavaScript 块时,这是正确的方法吗?更重要的是,在哪里以及如何应用正确的字符串替换代码来防止单引号变成 ',如下面的警报结果所示?
将其添加到单个脚本块中:
alert('@ViewBag.str') // "Hi, how's it going?"
导致以下警报:
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?
Adding this into a single script block:
alert('@ViewBag.str') // "Hi, how's it going?"
Results in the following alert:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Razor 将对所有内容进行 HTML 编码,因此为了防止 ' 被编码为
'
,您可以使用但是,现在您的字符串中间有一个实际的 ' ,这会导致JavaScript 错误。要解决此问题,您可以将警报字符串括在双引号(而不是单引号)中,或者转义 ' 字符。所以,在你的控制器中你会有
Razor will HTML encode everything, so to prevent the ' from being encoded to
'
, you can useHowever, 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
使用 JSON 字符串的另一种解决方案:
C#
Javascript
Another solution to use JSON string:
C#
Javascript