Question

I am using ASP.NET MVC Razor View to serialize an object to JSON. The output is correct in the debugger, but because it escapes every quote I think MVC may be trying to encode it because the final output ends up like this:

{"label":"Blowby","value":17},{"label":"BlownInsert","value":11},{"label":"Blowout","value":13},{"label":"Contamination","value":7},{"label":"CrushedInsert","value":3},{"label":"Reclaim","value":8},{"label":"ShortShot","value":4},{"label":"Sinks","value":10}

The json format is exactly what I want, but instead of &quot it needs to actual quotes. I have tried HtmlUtilites.HtmlDecode() with no luck. How can I fix the output?

Here is more of the code being used if it helps, this is inside a .cshtml/Razor file.

 List<LightSwitchApplication.Models.GraphData> DonutGraphData = (List<LightSwitchApplication.Models.GraphData>)ViewData["DonutGraphData"];
string donutSerialized = Newtonsoft.Json.JsonConvert.SerializeObject(DonutGraphData);

And the GraphData Class:

namespace LightSwitchApplication.Models
{
public class GraphData
{
    public string label { get; set; }
    public int value { get; set; }

    public GraphData(string label, int value)
    {
        this.label = label;
        this.value = value;
    }
}

}

And the actual variable being output to the View:

if ($('#donut-graph').length) {
            Morris.Donut({
                element: 'donut-graph',
                data: @donutSerialized,
                formatter: function (x) {
                    return x
                }
            });
        }

Here is the output of donutSerialized in the debugger:

"[{\"label\":\"Blowby\",\"value\":17},{\"label\":\"BlownInsert\",\"value\":11},{\"label\":\"Blowout\",\"value\":13},{\"label\":\"Contamination\",\"value\":7},{\"label\":\"CrushedInsert\",\"value\":3},{\"label\":\"Reclaim\",\"value\":8},{\"label\":\"ShortShot\",\"value\":4},{\"label\":\"Sinks\",\"value\":10}]"
Was it helpful?

Solution

Anything generated from C# will be HTML encoded by Razor by default.

So when you do @methodCall() it will be encoded.

If you want the value to stay as is, you can use @Html.Raw(@methodCall()).

Here is a quick link to a cheat sheet by Phil Haack - http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top