Google Chart in ASP.NET Core MVC 5

On the Visual Studio, select Create a new project from Get Started

Select ASP.NET Core Web Application




Input Project Name and select Location for new project

Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create button to finish




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

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCoreMVC5
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

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

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Demo}/{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 LearnASPNETCoreMVC5.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 LearnASPNETCoreMVC5.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 LearnASPNETCoreMVC5.Models;
using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreMVC5.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 5</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 5</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