如何将此 JSON 数据绑定到 Kendo UI 图表?

How do I bind this JSON data to a Kendo UI Chart?

我很难将 JSON 数据绑定到 ASP.Net MVC 中的 Kendo UI 图表。我一直在查看文档,拆解演示,搜索我在 SO(和其他地方)上可以找到的所有内容,试图找到我做错了什么的线索,这可以让我回到正轨,但我一直在打一堵砖墙我开始担心我脑残了,哈哈

这是我目前正在处理的内容:

JSON数据:

{  
   "responseHeader":{  
      "status":0,
      "QTime":6,
      "params":{  
         "indent":"true",
         "q":"*:*",
         "wt":"json"
      }
   },
   "response":{  
      "numFound":5,
      "start":0,
      "docs":[  
         {  
            "monthAndYear":"Apr 2015",
            "region":"Central Region",
            "projects_finalized":3,
            "_version_":1497873686497067008
         },
         {  
            "monthAndYear":"Apr 2015",
            "region":"Northern Region",
            "projects_finalized"1,
            "_version_":1497873686498115584
         },
         {  
            "monthAndYear":"Apr 2015",
            "region":"Eastern Region",
            "projects_finalized":1,
            "_version_":1497873686498115585
         },
         {  
            "monthAndYear":"Apr 2015",
            "region":"Southern Region",
            "projects_finalized":6,
            "_version_":1497873686498115586
         },
         {  
            "monthAndYear":"Apr 2015",
            "region":"Western Region",
            "projects_finalized":2,
            "_version_":1497873686498115588
         }
      ]
   }
}

这是我的模型:

public class Rootobject
{
    public Responseheader responseHeader { get; set; }
    public Response response { get; set; }
}

public class Responseheader
{
    public int status { get; set; }
    public int QTime { get; set; }
    public Params _params { get; set; }
}

public class Params
{
    public string indent { get; set; }
    public string q { get; set; }
    public string wt { get; set; }
}

public class Response
{
    public int numFound { get; set; }
    public int start { get; set; }
    public Doc[] docs { get; set; }
}

public class Doc
{
    public string monthAndYear { get; set; }
    public string region { get; set; }
    public int projects_finalized { get; set; }
    public long _version_ { get; set; }
}

这是我的观点:

@{
    ViewBag.Title = "Project Chart";
}

<div style="position: relative; left: 0px; top: 2em; width: 1000px; height: 100%; overflow: hidden; display: inline-block;">
@(Html.Kendo().Chart<ProjectChart.Models.ProjectClass>()
    .Name("barProjectsThisMonth")
    .Title("Project Results")
    .Legend(legend => legend
        .Visible(false)
    )
    .ChartArea(chartArea => chartArea
        .Background("transparent")
    )
    .DataSource(ds => ds.Read(read => read.Action("ProjectClass", "HomeController")))
    .Series(series =>
    {
        series.Bar(model => model.response.docs.projects_finalized).Name("Total Projects Completed")
              .Labels(labels => labels.Background("transparent").Visible(true));
    })
    .CategoryAxis(axis => axis
                .Categories(model => model.response.docs.region)
        .MajorGridLines(lines => lines.Visible(false))
    )
    .ValueAxis(axis => axis
        .Numeric()
        .MajorUnit(2)
        .Line(line => line.Visible(false))
        .MajorGridLines(lines => lines.Visible(true))
    )
    .Tooltip(tooltip => tooltip
        .Visible(true)
        .Template("#= series.name #: #= value #")
    )
    .Theme("MaterialBlack")
)
</div>

这是我的控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        return View();
    }

    [HttpPost]
    public ActionResult DataBinding()
    {
        string url = "https://solr.fakeURL.com/json";
        WebClient c = new WebClient();
        var json = c.DownloadString(url);

        return Json(json);
    }
}

为清楚起见,我无法对 JSON 的输出进行任何更改。我必须按照给定的条件工作。

Kendo 图表不仅接受任何 JSON 数据,格式正确很重要,通常使用 return Json(chartModel); 您无需担心这太多了。

在我看来,像这样将图表与数据源(Web 服务)紧密耦合也是糟糕的设计,但这与您当前的问题无关。

无论如何,我会执行以下操作:

在您的 business/data 访问层中,调用 Web 服务以获取 JSON,将 JSON 转换为 CLR 对象。您可以为此使用 Json.Net。

Rootobject result = JsonConvert.DeserializeObject<Rootobject>(jsonString);

转换 JSON 后,从数据中获取您的图表需要显示的内容(也许只是 projects_finalized?),然后 return 将其添加到您的图表中。

像这样:

public class ChartModel
{
    public string region { get; set; }
    public int projects_finalized { get; set; }
}

[HttpPost]
public ActionResult DataBinding()
{
    IEnumerable<ChartModel> result = GetData();
    return Json(result);
}

public IEnumerable<ChartModel> GetData() {
    string url = "https://solr.fakeURL.com/json";
    WebClient c = new WebClient();
    var json = c.DownloadString(url);

    // Do something like this to deserialize the JSON.
    Rootobject result = JsonConvert.DeserializeObject<Rootobject>(jsonString);

    // Here you flatten root object into collection of `ChartModel` objects

    return chartModels;
}

您可以尝试一种更简单的方法来开始,它只是将文档列表传递给视图并让它在客户端绑定

首先,将 json 反序列化为对象,在您的例子中,是 5 个文档

public ActionResult Index()
{
    ViewBag.Message = "Welcome to ASP.NET MVC!";
    var list = new List<Docs>();
    // deserialize json into list
    return View(list);
}

其次,更改视图,基本上从构造函数传递数据源并关闭服务器操作,如下所示。

@model List<Docs>
@(Html.Kendo().Chart<ProjectChart.Models.ProjectClass>(Model)
    .DataSource(d => d.ServerOperation(false))

您可能需要调整视图才能使其正常工作,但至少您的数据在那里。祝你好运