如何在使用chartjs创建图表时使用JSON数据?

时间:2018-02-09 15:00:56

标签: javascript jquery json chart.js

在我的控制器中,我有一个Action方法,可以在名为Questions的表格中找到所有问题,以及每个问题的答案。 此Action的类型为ContentResult,它将返回以Json格式序列化的结果。

public ContentResult GetData()
{
    var datalistQuestions = db.Questions.ToList();
    List<PsychTestViewModel> questionlist = new List<PsychTestViewModel>();
    List<PsychTestViewModel> questionanswerslist = new List<PsychTestViewModel>();
    PsychTestViewModel ptvmodel = new PsychTestViewModel();

    foreach (var question in datalistQuestions)
    {
        PsychTestViewModel ptvm = new PsychTestViewModel();
        ptvm.QuestionID = question.QuestionID;
        ptvm.Question = question.Question;
        questionlist.Add(ptvm);

        ViewBag.questionlist = questionlist;

        var agree = //query
        var somewhatAgree = //query
        var disagree = //query

        int Agree = agree.Count();
        int SomewhatAgree = somewhatAgree.Count();
        int Disagree = disagree.Count();

        ptvmodel.countAgree = Agree;
        ptvmodel.countSomewhatAgree = SomewhatAgree;
        ptvmodel.countDisagree = Disagree;

        questionanswerslist.Add(ptvmodel);
        ViewBag.questionanswerslist = questionanswerslist;
    }

    return Content(JsonConvert.SerializeObject(ptvmodel), "application/json");
}

现在,我的问题是饼图未创建,我不太清楚如何将值推送到我的数据结构中? 我应该做什么呢?

这是我的剧本:

@section Scripts {
    <script type="text/javascript">
           var PieChartData = {
                    labels: [],
                    datasets: [
                        {
                        label: "Agree",
                        backgroundColor:"#f990a7",
                        borderWidth: 2,
                        data: []
                        },
                    {

                        label: "Somewhat Agree",
                        backgroundColor: "#aad2ed",
                        borderWidth: 2,
                        data: []
                    },
                    {
                        label: "Disgree",
                        backgroundColor: "#9966FF",
                        borderWidth: 2,
                        data: []
                        },

                    ]
            };

            $.getJSON("/PsychTest/GetData/", function (data) {
            for (var i = 0; i <= data.length - 1; i++) {
                PieChartData.datasets[0].data.push(data[i].countAgree);
                PieChartData.datasets[1].data.push(data[i].countSomewhatAgree);
                PieChartData.datasets[2].data.push(data[i].countDisagree);
            }

            var ctx = document.getElementById("pie-chart").getContext("2d");

            var myLineChart = new Chart(ctx,
                {
                    type: 'pie',
                    data: PieChartData,
                    options:
                    {
                        responsive: true,
                        maintainaspectratio: true,
                        legend:
                        {
                            position : 'right'
                        }
                    }
                });
        });

</script>

2 个答案:

答案 0 :(得分:1)

您需要两个阵列来创建图表。其中一个表示标题,另一个表示每个标题的数量。你有客户端的标题,所以你只需要每个选项的数量,它可以从一个简单的服务器方法获取,如:

[HttpGet]  
public JsonResult Chart()
{
    var data = new int[] { 4, 2, 5 }; // fill it up whatever you want, but the number of items should be equal with your options
    return JsonConvert.SerializeObject(data)
}

客户端代码在这里:

        var aLabels = ["Agree","Somewhat Agree","Disagree"];
        var aDatasets1 = [4,2,5]; //fetch these from the server   

        var dataT = {  
            labels: aLabels,  
            datasets: [{  
                label: "Test Data",  
                data: aDatasets1,  
                fill: false,  
                backgroundColor: ["rgba(54, 162, 235, 0.2)", "rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],  
                borderColor: ["rgb(54, 162, 235)", "rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],  
                borderWidth: 1  
                }]  
            };  
            
            var opt = {  
                responsive: true,  
                title: { display: true, text: 'TEST CHART' },  
                legend: { position: 'bottom' },  
                //scales: {
//    xAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' } }],  
//    yAxes: [{ gridLines: { display: false }, display: true, scaleLabel: { display: false, labelString: '' }, ticks: { stepSize: 50, beginAtZero: true } }]  
//}
            };
            
        var ctx = document.getElementById("myChart").getContext("2d");
        var myNewChart = new Chart(ctx, {  
            type: 'pie',  
            data: dataT,  
            options: opt  
        }); 
<script src="https://github.com/chartjs/Chart.js/releases/download/v2.7.1/Chart.min.js"></script>


<div Style="font-family: Corbel; font-size: small ;text-align:center " class="row">  
    <div  style="width:100%;height:100%">  
            <canvas id="myChart" style="padding: 0;margin: auto;display: block; "> </canvas>  
    </div>  
</div>  

答案 1 :(得分:0)

如果你仍然希望将json用于chart.js图表​​。

这是一个获取json文件并在chart.js图表​​上呈现它的解决方案。

    fetch('https://s3-us-west-2.amazonaws.com/s.cdpn.io/827672/CSVtoJSON.json')
      .then(function(response) {
        return response.json();
      })
      .then(function(ids) {

      new Chart(document.getElementById("bar-chart"), {
        type: 'bar',
        data: {
          labels: ids.map(function(id) {
                  return id.Label;
                  }),
          datasets: [
            {
              label: "value2",
              backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
              data: ids.map(function(id) {
                    return id.Value2;
                    }),
            },
             {

              label: "value",
              //backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
              data: ids.map(function(id) {
                    return id.Value;
                    }),
            },
          ]
        },
        options: {
          legend: { display: false },
          title: {
            display: true,
            text: 'Sample Json Data Chart'
          }
        }
    });

});

see running code on jsfiddle here