Passing strings with Single Qoute from MVC Razor to JavaScript
Asked Answered
L

2

22

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

Lapp answered 21/4, 2011 at 20:43 Comment(0)
A
40

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?";
Adjudicate answered 22/4, 2011 at 0:28 Comment(2)
If you'd rather not have to re-escape strings, try @Html.Raw(String.Format("var str = \"{0}"\", ViewBag.str) followed by alert(str);Furious
Isn't this a huge risk for script injection?Cowherd
W
0

Another solution to use JSON string:

C#

ViewBag.str = "[{\"Text\":\"Hi, how's it going?\"}]";

Javascript

var j = @Html.Raw(ViewBag.str);
alert (j[0].Text); 
Wobble answered 28/1, 2021 at 19:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.