Passing strings with Single Qoute from MVC Razor to JavaScript

久未见 提交于 2019-12-20 18:31:54

问题


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 &#39 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:


回答1:


Razor will HTML encode everything, so to prevent the ' from being encoded to ', you can use

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

ViewBag.str = "Hi, how\\'s it going?";


来源:https://stackoverflow.com/questions/5749590/passing-strings-with-single-qoute-from-mvc-razor-to-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!