Lobsterpants
Lobsterpants

Reputation: 1258

Google Charts and asp.net MVC

I am trying to create a simple chart using Google Charts and data provided by an Asp.net controller.

this is the controller action:

public JsonResult HierachyChart(int id)
    {
        List<object> rows = new List<object>
        {
            new{ cols =  new object[] { "Employee Name", "Salary" }},
            new {rows =  new object[]
            {
                new object[] { "Bob", 35000 },
            new object[] { "Alice", 44000 },
            new object[] { "Frank", 27000 },
            new object[] { "Floyd", 92000 },
            new object[] { "Fritz", 18500 }
                }
        }};

        return this.Json(rows, JsonRequestBehavior.AllowGet);
    }

Which seems to be as simple as I can make it and returns this when I run it:

[{"cols":["Employee Name","Salary"]},
 {"rows":[["Bob",35000],["Alice",44000],["Frank",27000],["Floyd",92000],["Fritz",18500]]}]

Which to the untrained eye appears to be the right format ?

    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">

    google.charts.load("current", {packages:["corechart"]});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
        var jsonData = $.ajax({
            url: '@Url.Action("HierachyChart", "JobHierachy", new { Id = 1538 })',
            dataType: "json",
            async: false
        }).responseText;

        // Create our data table out of JSON data loaded from server.
        var data = new google.visualization.DataTable(jsonData);

        // Instantiate and draw our chart, passing in some options.
        var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
        chart.draw(data, {width: 400, height: 240});
    }
</script>

But whenI run it I simply get Table has no columns

What am I doing wrong?

Upvotes: 4

Views: 3227

Answers (3)

shanika chamodi
shanika chamodi

Reputation: 21

 <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.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
        // Load the Visualization API and the corechart package.
        google.charts.load('current', {'packages':['corechart']});
        // Set a callback to run when the Google Visualization API is loaded.
        google.charts.setOnLoadCallback(drawChart);
        // Callback that creates and populates a data table,  instantiates the pie chart, passes in the data and draws it.
        function drawChart() {
            // Create the data table.
            $.ajax({
                type: "POST",
                url: "Googlechart.aspx/GetChartData",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    var chartdata = new google.visualization.DataTable();
                    chartdata.addColumn('string', 'Date');
                    chartdata.addColumn('number', 'Sales Amount');
                    chartdata.addRows( r.d);
                    var options = {'title':'Date Wise Sales Summary',
                        'width':1000,
                        'height': 500
                    };// Instantiate and draw our chart, passing in some options.
                    var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
                    chart.draw(chartdata, options);
                },
                failure: function (r) {
                    alert(r.d);
                },
                error: function (r) {
                    alert(r.d);
                }
            });
        }
    </script>

Refer for-https://aspguru.online/How-to-create-google-charts-in-Asp-Net.html

Upvotes: 2

Lobsterpants
Lobsterpants

Reputation: 1258

Building on what @Isma was saying I finally got it working by specifying the values like this:

        public class HierarchyChart
    {
        public object[] cols { get; set; }
        public object[] rows { get; set; }
    }

    public JsonResult HierachyChart(int id)
    {
        var hierarchyChart = new HierarchyChart
        {
            cols = new object[]
            {
                new { id = "task", type = "string", label = "Employee Name" },
                new { id = "startDate", type = "date", label = "Start Date" }
            },
            rows = new object[]
            {
                new { c = new object[] { new { v = "Bob" }, new { v = 35000 } } },
                new { c = new object[] { new { v = "Alice" }, new { v = 44000 } } },
                new { c = new object[] { new { v = "Frank" }, new { v = 28000 } } },
                new { c = new object[] { new { v = "Floyd" }, new { v = 92000 } } },
                new { c = new object[] { new { v = "Fritz" }, new { v = 18500 } } }
            }
        };

        return this.Json(hierarchyChart, JsonRequestBehavior.AllowGet);
    }

Hope that helps anyone searching for this

Upvotes: 0

Isma
Isma

Reputation: 15190

I think the problem is the first list, you could try to encapsulate the result using a parent class:

public class HierarchyChart
{
    public object[] cols { get; set; }
    public object[] rows { get; set; }
}

public JsonResult HierachyChart(int id)
{
    var hierarchyChart = new HierarchyChart();
    hierarchyChart.cols = new object[] { "Employee Name", "Salary" }
    hierarchyChart.rows = new object[] {
        new object[] { "Bob", 35000 },
        new object[] { "Alice", 44000 },
        new object[] { "Frank", 27000 },
        new object[] { "Floyd", 92000 },
        new object[] { "Fritz", 18500 }
    };

    return this.Json(hierarchyChart , JsonRequestBehavior.AllowGet);
}

This is the output now:

{"cols":["Employee Name","Salary"],"rows":[["Bob",35000],["Alice",44000],["Frank",27000],
    ["Floyd",92000],["Fritz",18500]]}

Upvotes: 4

Related Questions