Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing strings with Single Qoute from MVC Razor to JavaScript

Tags:

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:

enter image description here

like image 538
user646306 Avatar asked Apr 21 '11 20:04

user646306


People also ask

How do I pass a single quote in JavaScript?

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.

How do you pass a single quote in a 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.

Does JavaScript accept single and double quotes?

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!

How do you quote a string in JavaScript?

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 \ .


1 Answers

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?"; 
like image 105
ataddeini Avatar answered Sep 19 '22 17:09

ataddeini