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:
We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
Enclosing Quotation Marks That means strings containing single quotes need to use double quotes and strings containing double quotes need to use single quotes. "It's six o'clock."; 'Remember to say "please" and "thank you."'; Alternatively, you can use a backslash \ to escape the quotation marks.
Both single (' ') and double (" ") quotes are used to represent a string in Javascript. Choosing a quoting style is up to you and there is no special semantics for one style over the other. Nevertheless, it is important to note that there is no type for a single character in javascript, everything is always a string!
If you have single quotes in the string, delimit it with double quotes. If you have double quotes in the string, delimit it with single quotes. If you need to use both types in the string, escape whatever delimiter you have chosen by prefixing it with a \ .
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?";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With