JSON C# 中 Highcharts 数据对象的结果

JSON Result for Highcharts Data Object in C#

我正在尝试获取自定义 class 的列表,并在 MVC/C# 中将其转换为 JSON。我使用了 json.encode 和 javascriptserializer 都无济于事。 json 数据显示为“.quot;”。而不是单引号或双引号。这是我认为相关的代码。此数据将用于 highcharts 应用程序。

我的模特

public class DataPoint
{
    public double? data { get; set; } //CTDI value
    public DateTime? DateOfScan { get; set; }
    public string Name { get; set; }
    public string Nmmber{ get; set; }
    public int PersonDatabaseID { get; set; }
    public string EquipmentName{ get; set; }
}

public class PlotData : List<DataPoint>
{
}

public class PlotListModel : List<PlotData>
{
}

我的观点

foreach (PlotData pd in (PlotListModel) ViewBag.MyData)
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    var jsData1 = js.Serialize(pd);

    //Or use JSON.Encode
    var jsData2 = Json.Encode(pd);

    string divID = "container" + i;
    <div id='@divID'>
        <script type='text/javascript'>
            $(function () {
                var chart = new Highcharts.Chart({
                    chart: {
                        renderTo: '@divID',
                        type: 'colummn'
                    },
                    title: {text: '@divID'},
                    tooltip: {
                        formatter: function () {
                            return 'Extra data: <b>' + this.point.Scanner + '</b>';
                        }
                    },

                    series: [{
                        name: 'Foo',
                        data: ['@jsData1']
                    }]
                });
            });
        </script>
    </div>

    i += 1;
}

When I look at the page source I see the data fields and values surrounded by the encoded quote value - &quot;

您应该创建一个 webapi 控制器,它应该包含一个看起来像这样的方法。我假设您在此示例中使用的是 Web Api 2.0。

[Route("api/plotlist")]
[HttpGet]
public PlotListModel GetPlotList() {
    //Here's where you would instantiate and populate your model
    PlotListModel plotList; 

    /*
     * Once your model is instantiated and populated then you can
     * just return it and the serialization will be done for you
     */

    return plotList;
}

一旦你有了它,你就可以使用 ajax 从你的客户端代码中调用该方法。如果您使用 jQuery.

,一个简单的客户端函数可能看起来像这样
function retreivePlotList() {
    $.getJSON("http://<base url>/api/plotlist", function(data) { 
        //do something with data 
    });
}

这是网页 api class

public class PlotListController : ApiController
{
    [Route("api/plotlist")]
    [HttpGet]
    public IEnumerable<CTDIDataPoint> GetPlotList()
    {....

当我输入 localhost/api/plotlist 时出现 404 错误

这是网络api配置。

public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }