通过单Qoute字符串从MVC剃刀的JavaScript [英] Passing strings with Single Qoute from MVC Razor to JavaScript
问题描述
这看起来很简单很尴尬。然而,第一个问题是来自新ViewBag在MVC 3.0(剃刀)传递一个值到一个JavaScript块的时候,这是做了正确的方法是什么?更重要的是,在这里,你如何成为&#39应用适当的字符串替换code至prevent一个单引号如下得到警报?
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?
添加此成一个脚本块:
alert('@ViewBag.str') // "Hi, how's it going?"
结果如下警告:
推荐答案
剃刀将HTML带code一切,所以到prevent的'被连接coded到&放;#39;
,您可以用
Razor will HTML encode everything, so to prevent the ' from being encoded to '
, you can use
alert('@Html.Raw(ViewBag.str)');
不过,现在你已经得到了你的字符串中间这会导致JavaScript错误的实际。为了解决这个问题,你可以包裹在双引号警报字符串(而不是单引号),或逃避字符。所以,在你的控制器你会
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
ViewBag.str = "Hi, how\\'s it going?";
这篇关于通过单Qoute字符串从MVC剃刀的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!