Google Chart in ASP.NET Core MVC

On the Visual Studio, create new ASP.NET Core Web Application project

Select Empty Template

Click Ok button to Finish




Open Startup.cs file and add new configurations as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace LearnASPNETCoreMVCWithRealApps
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Product}/{action=Index}/{id?}");
            });

        }
    }
}

Create new folder named Models. In Models folder, create new entity class as below:

Create new class named Product.cs as below:

namespace LearnASPNETCoreMVCWithRealApps.Models
{
    public class Product
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int Quantity { get; set; }
    }
}




Create new folder named Controllers. In this folder, create new controller named ProductController.cs as below:

using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreMVCWithRealApps.Controllers
{
    [Route("product")]
    public class ProductController : Controller
    {
        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
            return View();
        }
    }
}

In Controllers folder, create new class named ProductRestController.cs as below:

using System.Collections.Generic;
using System.Threading.Tasks;
using LearnASPNETCoreMVCWithRealApps.Models;
using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreMVCWithRealApps.Controllers
{
    [Route("api/product")]
    public class ProductRestController : Controller
    {

        [HttpGet("findall")]
        [Produces("application/json")]
        public async Task<IActionResult> findAll()
        {
            try
            {
                var products = new List<Product>
                {
                    new Product { Id = "p01", Name = "Product 1", Price = 100, Quantity = 20 },
                    new Product { Id = "p02", Name = "Product 2", Price = 120, Quantity = 12 },
                    new Product { Id = "p03", Name = "Product 3", Price = 80, Quantity = 60 },
                    new Product { Id = "p04", Name = "Product 4", Price = 290, Quantity = 34 },
                    new Product { Id = "p05", Name = "Product 5", Price = 200, Quantity = 29 }
                };
                return Ok(products);
            }
            catch
            {
                return BadRequest();
            }
        }
    }
}




Create new folder named Views. In this folder, create new folder named Product. Create new view named Index.cshtml as below:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Google Chart in ASP.NET Core MVC</title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script>

        $(document).ready(function () {

            $.ajax({
                type: 'GET',
                dataType: "json",
                contentType: "application/json",
                url: '/api/product/findall',
                success: function (result) {
                    google.charts.load('current', {
                        'packages': ['corechart']
                    });
                    google.charts.setOnLoadCallback(function () {
                        drawChart(result);
                    });
                }
            });

            function drawChart(result) {

                var data = new google.visualization.DataTable();
                data.addColumn('string', 'Name');
                data.addColumn('number', 'Quantity');
                var dataArray = [];
                $.each(result, function (i, obj) {
                    dataArray.push([obj.name, obj.quantity]);
                });

                data.addRows(dataArray);

                var piechart_options = {
                    title: 'Pie Chart: How Much Products Sold By Last Night',
                    width: 400,
                    height: 300
                };
                var piechart = new google.visualization.PieChart(document
                    .getElementById('piechart_div'));
                piechart.draw(data, piechart_options);

                var barchart_options = {
                    title: 'Barchart: How Much Products Sold By Last Night',
                    width: 400,
                    height: 300,
                    legend: 'none'
                };
                var barchart = new google.visualization.BarChart(document
                    .getElementById('barchart_div'));
                barchart.draw(data, barchart_options);
            }


        });

    </script>

</head>
<body>

    <h3>Google Chart in ASP.NET Core MVC</h3>
    <table class="columns">
        <tr>
            <td><div id="piechart_div" style="border: 1px solid #ccc"></div></td>
            <td><div id="barchart_div" style="border: 1px solid #ccc"></div></td>
        </tr>
    </table>

</body>
</html>




Access Index action in Product controller with following url: http://localhost:48982/Product/Index

Output