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

时间:2015-04-08 17:48:39

标签: c# json asp.net-mvc kendo-ui kendo-asp.net-mvc

我很难将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的输出进行任何更改。我必须与给定的东西一起工作。

2 个答案:

答案 0 :(得分:0)

剑道图表不仅接受任何JSON数据,因此格式正确非常重要,通常使用return Json(chartModel);您无需过多担心。

在我看来,将图表与您的数据源(网络服务)紧密结合在一起也是不好的设计,但这与您当前的问题无关。

无论如何,我会做以下事情:

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

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

转换完JSON后,从数据中获取图表需要显示的内容(可能只有projects_finalized?)并将其返回到图表中。

这样的事情:

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;
}

答案 1 :(得分:0)

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

首先,将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))

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