How to use JSON data in creating a chart with chartjs?

Bumblebeeee

In my controller I have an Action method that will find all questions in a table called Questions, and the answers for each question. This Action is of type ContentResult that will return a result serialized in Json format.

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

Now, my problem is the pie chart is not being created and I don't quite know how to push the values to my data structure? What should I be doing instead?

Here is my script:

@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>
Pedram

You need two arrays for creating your chart. One of them indicates titles and another one shows the number of each titles. You have titles in the client side, so you only need the number of each options and it could be fetched from a simple server method like:

[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)
}

The client side code is here:

        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>  

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related