简体   繁体   中英

JavaScript crashing due to HTML entities in JSON string

I am using NewtonSoft.Json.JsonConvert.SerializeObject() to serialize an ASP.NET Dictionary object into a JSON string. I then pass this string to my MVC View by means of the ViewBag.

When I in my MVC Razor by Razor syntax try to load the JSON string from the ViewBag and into a JavaScript variabe my JavaScript crashes due to syntax error. When I inspect the source code I find this:

var hf = {"Test0":65,"Test1":23,"Test2":43,"Test3":6,"Test4":31,"Test5":78,"Test6":1,"Test7":53,"Test8":74,"Test9":54};

This my logic for loading the contents of the ViewBag in the View:

@section RenderChart
{
<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });
    function drawChart() {
        var hf = @ViewBag.ChartJsonData;

For some reason my JSON string is being HTML encoded. I tried passing it into the ViewBag after running it through Server.HtmlDecode() but that did not help. Does anyone know how I can decode this string or pass it to the JavaScript in my MVC View without it being converted to HTML entities?

Razor automatically HTML encodes every string if it was outputted with the @ .

If you don't want the HTML encoding you need to wrap your string with a Html.Raw :

<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });
    function drawChart() {
        var hf = @Html.Raw(ViewBag.ChartJsonData)
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM