Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
-6
rated 0 times [  0] [ 6]  / answers: 1 / hits: 18493  / 13 Years ago, thu, april 21, 2011, 12:00:00

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


More From » asp.net-mvc

 Answers
9

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?;

[#92620] Tuesday, April 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shawn

Total Points: 507
Total Questions: 103
Total Answers: 111

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
shawn questions
Tue, Aug 10, 21, 00:00, 3 Years ago
Tue, Jun 8, 21, 00:00, 3 Years ago
Sat, Feb 27, 21, 00:00, 3 Years ago
Sat, Dec 19, 20, 00:00, 4 Years ago
Sat, May 9, 20, 00:00, 4 Years ago
;