Search code examples
c#asp.net-coregoogle-visualization

Google chart for asp.net core Razor Pages


I am following this tutorial https://dotnetthoughts.net/integrating-google-charts-in-aspnet-core/ and am stuck trying to load the chart data from the Index.cshtml.cs page via the 'OnGetChartData' ActionResult. I get an 'Failed to load resource: the server responded with a status of 404 ()' exception and the console pointing to Index?handler=OnGetChartData. The problem seems to be in the url specification but I have not managed to figure out the correct string.

Any suggestions are appreciated!

    public ActionResult OnGetChartData()
    {
        var pizza = new[]
{
                    new {Name = "Mushrooms", Count = 4},
                    new {Name = "Onions", Count = 1},
                    new {Name = "Olives", Count = 1},
                    new {Name = "Zucchini", Count = 1},
                    new {Name = "Pepperoni", Count = 2}
                };

        var json = pizza.ToGoogleDataTable()
                .NewColumn(new Column(ColumnType.String, "Topping"), x => x.Name)
                .NewColumn(new Column(ColumnType.Number, "Slices"), x => x.Count)
                .Build()
                .GetJson();

        return Content(json);
    }

Here is the scripts section: drawChart1 works as expected.

@section Scripts {

    // Load the Visualization API and the corechart package
    google.charts.load('current', { 'packages': ['corechart'] });

    // Set a callback to run for each chart when the Google Visualization API is loaded.
    google.charts.setOnLoadCallback(drawChart1);
    google.charts.setOnLoadCallback(drawChart2);

    // Callback that creates and populates a data table,
    // instantiates the pie chart, passes in the data and
    // draws it.
    function drawChart1() {

        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Topping');
        data.addColumn('number', 'Slices');
        data.addRows([
            ['Mushrooms', 3],
            ['Onions', 1],
            ['Olives', 1],
            ['Zucchini', 1],
            ['Pepperoni', 2]
        ]);

        // Set chart options
        var options = {
            'title': 'How Much Pizza I Ate Last Night',
            'width': 400,
            'height': 300
        };

        // Instantiate and draw our chart, passing in some options.
        var chart1 = new google.visualization.PieChart(document.getElementById('chart1'));
        chart1.draw(data, options);
    }
    function drawChart2() {

        // Create the data table.
        var jsonData = $.ajax({
            url: "/Index?handler=OnGetChartData",
            dataType: "json",
            async: true
        }).responseText;
        var data = new google.visualization.DataTable(jsonData);

        // Set chart options
        var options = {
            'title': 'How Much Pizza I Ate Last Night',
            'width': 400,
            'height': 300
        };

        // Instantiate and draw our chart, passing in some options.
        var chart2 = new google.visualization.PieChart(document.getElementById('chart2'));
        chart2.draw(data, options);
    }
</script>

Solution

  • Rewrote the answer, in the first attempt i missed the fact this was razor pages ...

    The url should be

    url: "/Index?handler=ChartData"
    

    and not

    url: "/Index?handler=OnGetChartData"
    

    The OnGet part of the method name just indicates this method is a HTTP Get.

    You can even simplify it further by removing the /Index and just use

    url: "?handler=ChartData"
    

    I expect your PageModel class to look something like this

    public class IndexModel : PageModel {
       ...      
       public ActionResult OnGetChartData()  {
       ...
       }
    }
    

    You can just paste the url directly into the browser to ensure it returns something reasonable enter image description here