1

I am working on an MVC project and are passing a string to the view through the ViewData. The string has single quotes, double quotes and other special characters (to give some background, I am following the store locator tutorial as a test project, but using Razor instead of asp.net.)

As soon as the variable hits the Javascript tags, the special characters get decoded onto HTML. For example:

storeList =  [{ title: 'Location # 12', position: new google.maps.LatLng(32.85914441, -96.9444170)},{ title: 'Location # 7', position: new google.maps.LatLng(32.855526, -96.9555080)}]....

When it should contain:

storeList =  [{ title: 'Location # 12', position: new google.maps.LatLng(32.85914441, -96.9444170)},{ title: 'Location # 7', position: new google.maps.LatLng(32.855526, -96.9555080)}] ....

I have tried the solution listed on this question but have not been successful:

<script type="text/javascript">
var storeList = $("<div/>").html(@ViewData["storeList"]).text();

But I get an error regardless:

"Uncaught SyntaxError: Unexpected token &" 

And the error starts at the &#39:

var storeList = $("<div/>").html([{ title: &#39;Location # 12&#39;, position: .....

Any help would be very appreciated. Thanks!

Community
  • 1
  • 1
Irina
  • 1,333
  • 3
  • 17
  • 37

2 Answers2

2

Use @Html.Raw to skip the html escaping with Razor.

Jonathan Dion
  • 1,651
  • 11
  • 16
1

try Html.Raw() to insert the html unescaped.

fastr.de
  • 1,497
  • 14
  • 23