Thursday, April 29, 2021

MVC Bar Chart using JQuery



    Step1. Create a MVC Project in Visual Studio
    Step2. Download script and add JQuery script inside Index.cshtml inside Scripts
    Step3. Create a HTML canvas with id.
    Step4. Use JavaScript code inside JQuery function inside script tag to access the canvas using id and draw chart on this canvas.
    Step5. Create models as per the JSON data, example is based on illustraive data displayed on the site

Barchart.cs Model file code: It contains two classes namely Barchart and BarchartDataset. The model is based on the static data displayed at https://www.chartjs.org/docs/latest/
It is also copied below.
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});
</script>

The code of Barchart.cs 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcJQueryChartPie.Models
{
    public class Barchart
    { 
        public List<string> labels { get; set; }
        public List<BarchartDataset> datasets { get; set; }
        
        public Barchart()
        {
            labels = new List<string>();
            datasets = new List<BarchartDataset>();
        }

    }

    public class BarchartDataset
    {
        //public string title { get; set; }
        public List<int> data { get; set; }
        public List<string> backgroundColor { get; set; }
        //public List<string> borderColor { get; set; }
        public BarchartDataset()
        {
            //title = string.Empty;
            data = new List<int>();
            backgroundColor = new List<string>();
            //borderColor = new List<string>();
        }

    }
}

The code of Index.cshtml

@using MvcJQueryChartPie.Models
@model BarChartInitializer 

@{
    ViewBag.Title = "Home Page";
}
@*/*
    Step1. Create a MVC Project in Visual Studio
    Step2. Download script and add JQuery script inside Index.cshtml inside Scripts
    Step3. Create a HTML canvas with id.
    Step4. Use JavaScript code inside JQuery function inside script tag to access the canvas using id and draw chart on this canvas.
    Step5. Create models as per the JSON data, example is based on illustraive data displayed on the site
    */*@
<div class="row">
    <div class="col-md-8">
        <canvas id="barchartcanvas" width="400" height="250"></canvas>
    </div>
</div>
@section Scripts{

    <script src="~/Scripts/chartjs.js"></script>
    <script type="text/javascript">
        $(function () {


            var ctx = document.getElementById('barchartcanvas').getContext('2d');
            var myChart = new Chart(ctx, {
                type: 'bar',
                data: @Html.Raw(Json.Encode(Model.barchart)),
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        });
    </script>
}

NOTE Read about canvas at the Mozilla site 

@HTML.Raw is used to show the data without HTML encoding.

The code of HomeController.cshtml

using MvcJQueryChartPie.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcJQueryChartPie.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            BarChartInitializer objBarchartInit = new BarChartInitializer();
            var barchartData = GetbarchartData();
            objBarchartInit.barchart = barchartData;
            return View(objBarchartInit);
        }

        private Barchart GetbarchartData()
        {
            var objBarchart = new Barchart();
            //add labels list to objBarchart
            var labelList = new List<string> { "Red", "Green", "Blue", "Pink", "Coral" };
            objBarchart.labels.AddRange(labelList);
            //
            var dataList = new List<int>();
            var bgColorList = new List<string>();
            foreach (var label in labelList)
            {
                if (label=="Red")
                {
                    dataList.Add(5);
                    bgColorList.Add("rgba(255, 0, 0, 0.9)");
                }
                if (label == "Green")
                {
                    dataList.Add(9);
                    bgColorList.Add("rgba(0, 255, 0, 0.9)");
                }
                if (label == "Blue")
                {
                    dataList.Add(10);
                    bgColorList.Add("rgba(0, 0, 255, 0.9)");
                }
                if (label == "Pink")
                {
                    dataList.Add(4);
                    bgColorList.Add("rgba(255, 192, 203, 0.9)");
                }
                if (label == "Coral")
                {
                    dataList.Add(3);
                    bgColorList.Add("rgba(255, 127,80, 0.9)");
                }
            }
            BarchartDataset objdataSet = new BarchartDataset();
            //objdataSet.data=dataList; // it will work also
            objdataSet.data.AddRange(dataList);
            //objdataSet.backgroundColor = bgColorList; // it will work also
            objdataSet.backgroundColor.AddRange(bgColorList);
            objBarchart.datasets.Add(objdataSet);

            return objBarchart;
        }
    }
}
 

NOTE: We create collection/List of bgColorList and dataList. They are initialized for each label value.

No comments:

Post a Comment

Hot Topics