sqlasp.net-mvcgoogle-visualizationgoogle-pie-chart

How to display jsonresult data as a chart view and not an array in asp.net mvc using google charts (pie)


I am trying to display a google pie chart based on a particular query but the result i get is: [["Status","TotalProgress"],["Completed",1],["In-Progress",2],["To-Do",1]] it should be:

expected pie chart in my code the scenario is as follows: a supervisor wants to view a selected students progress: controller method(i used this tutorial but it does not include the "id" factor): link to tutorial i used

controller method:

 public JsonResult AjaxMilestoneStatus(string id)
    {

        string query = $"SELECT Status, COUNT(Progress) AS TotalProgress from Milestone  
       Where StudentNumber = '{id}' GROUP BY Status";
        // string query = "SELECT Status, COUNT(Progress) AS TotalProgress from 
       Milestone GROUP BY Status ";

        string constr = 
         ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        List<object> chartData = new List<object>();
        chartData.Add(new object[]
                        {
                        "Status", "TotalProgress"
                        });
        using (var con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        chartData.Add(new object[]
                        {
                        sdr["Status"], sdr["TotalProgress"]
                        });
                    }
                }

                con.Close();
            }
        }

        return Json(chartData, JsonRequestBehavior.AllowGet);
    }

then the view looks like this:

enter code here

<!DOCTYPE HTML>
<html>
<head>
<script src="~/Scripts/jquery-3.3.1.js"></script>


</head>
<body>
<h1></h1>

@*<div id="chartContainer" style="height: 370px; width: 100%;"></div>*@
<script type="text/javascript" 
src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {
         $.ajax({
            type: "Get",
             url: "/CHART/AjaxMilestoneStatus",

            data: '{id: id}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                var data =  google.visualization.arrayToDataTable(r);

                //Pie
                var options = {
                    title: 'My Progress'
                };
                var chart = new google.visualization.PieChart($("#chart")[0]);

                chart.draw(data,options);
            },
            failure: function (r) {
                alert(r.d);
            },
            error: function (r) {
                alert(r.d);
            }

        });
    }
   </script>

   <div id="chart" style="width: 500px; height: 400px;"></div>

`

i had read somewhere that i should call the jsonresult method to a view in my controller if this is the way i should do it please assist me, i have really struggled, please help! thank you.


Solution

  • enter image description here

    View

    @{
        Layout = null;
    }
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
    </head>
    <body>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript" src="https://www.google.com/jsapi"></script>
        <script type="text/javascript">
            google.load("visualization", "1", { packages: ["corechart"] });
            google.setOnLoadCallback(drawChart);
            function drawChart() {
                $.ajax({
                    type: "GET",
                    //my url is different than yours
                    //url: "/CHART/AjaxMilestoneStatus",
                    url: "/Home/AjaxMilestoneStatus",
                    //took off parens in my data
                    data: { id: $("#aHidden").val() },
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        var data = google.visualization.arrayToDataTable(r);
                        //Pie
                        var options = {
                            title: 'My Progress'
                        };
                        var chart = new google.visualization.PieChart($("#chart")[0]);
                        chart.draw(data, options);
                    },
                    failure: function (r) {
                        alert(r.d);
                    },
                    error: function (r) {
                        alert(r.d);
                    }
                });
            }
        </script>
        <input type="hidden" id="aHidden" value="2" />
        <div id="chart" style="width: 500px; height: 400px;">
        </div>
    </body>
    </html>
    

    Controller

        public JsonResult AjaxMilestoneStatus(string id)  
        {
            //swapped {id} with {0}
            string query = String.Format(@"SELECT Status, COUNT(Progress) AS TotalProgress from Milestone Where StudentNumber = '{0}' GROUP BY Status",
                                            id);
    
            string constr =
             ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
    
            List<object> chartData = new List<object>();
            chartData.Add(new object[]
                        {
                        "Status", "TotalProgress"
                        });
            using (var con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            chartData.Add(new object[]
                        {
                        sdr["Status"], sdr["TotalProgress"]
                        });
                        }
                    }
    
                    con.Close();
                }
            }
    
            return Json(chartData, JsonRequestBehavior.AllowGet);
        }