在ASP.NET MVC视图中,Newtonsoft Json.NET序列化对象无法正确呈现

Lan*_*ond 0 c# asp.net asp.net-mvc json json.net

我正在使用ASP.NET MVC Razor View将对象序列化为JSON.调试器中的输出是正确的,但因为它逃脱了每个引用,我认为MVC可能正在尝试对其进行编码,因为最终输出最终会像这样:

{"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}
Run Code Online (Sandbox Code Playgroud)

json格式正是我想要的,但不是"它需要实际的引号".我没试过HtmlUtilites.HtmlDecode().我该如何修复输出?

如果它有帮助,这里有更多的代码,这是在.cshtml/Razor文件中.

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

和GraphData类:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

}

并且实际变量输出到View:

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

以下是调试器中donutSerialized的输出:

"[{\"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}]"
Run Code Online (Sandbox Code Playgroud)

Yis*_*zer 6

默认情况下,由C#生成的任何内容都将由Razor进行HTML编码.

因此,当你执行@methodCall()时,它将被编码.

如果希望值保持不变,可以使用@ Html.Raw(@methodCall()).

以下是Phil Haack的备忘单快速链接 - http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/