Thursday 11 February 2021

MVC - Chart.js - Create simple Multi Line Chart and load data using Entity Framework

 Watch this example on YouTube


 

1. Table

 

USE [Company]
GO
/****** Object:  Table [dbo].[ChartTest]    Script Date: 2021-02-09 4:17:58 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ChartTest](
    [ProductName] [varchar](50) NULL,
    [Month] [varchar](50) NULL,
    [Amount] [int] NULL,
    [MonthNumber] [int] NULL
) ON [PRIMARY]

GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Apple', N'Jan', 20, 1)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Apple', N'Feb', 40, 2)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Apple', N'Mar', 22, 3)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Apple', N'Apr', 44, 4)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Orange', N'Jan', 55, 1)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Orange', N'Feb', 22, 2)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Orange', N'Mar', 33, 3)
GO
INSERT [dbo].[ChartTest] ([ProductName], [Month], [Amount], [MonthNumber]) VALUES (N'Orange', N'Apr', 88, 4)
GO

2. Stored Procedure

-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
CREATE PROCEDURE SelectChartTest
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT * From ChartTest
END
GO
 

3.Layout


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/Scripts/jquery-1.10.2.min.js")
    @Scripts.Render("~/Scripts/Chart.js")
    @Scripts.Render("~/Scripts/Common.js")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

4. Common.js

jQuery.extend({
    getValues: function (url) {
        var result = null;
        $.ajax({
            url: url,
            type: 'get',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            async: false,
            success: function (data) {
                result = data;
            }
        });
        return result;
    }

});


5. Model

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

namespace BarChartMulti.Models
{
    public class Chart
    {
        public string[] labels { get; set; }
        public List<Datasets> datasets { get; set; }
    }
    public class Datasets
    {
        public string label { get; set; }
        public string[] backgroundColor { get; set; }
        public string[] borderColor { get; set; }
        public string borderWidth { get; set; }
        public int[] data { get; set; }
    }
}


6. Controller

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

namespace BarChartMulti.Controllers
{
    public class HomeController : Controller
    {
        CompanyEntities db = new CompanyEntities();

       public JsonResult MultiLineChartData()
        {
            var data = db.SelectChartTest().ToList();
            var uniqueProducts = from d in data orderby d.ProductName group d by d.ProductName into m select m.Key;
            var uniqueMonths = from a in data orderby a.MonthNumber group a by a.Month into g select g.Key;
            string[] cols = new string[] { "#FF0000", "#800000" };
            int i = 0;
            Chart _chart = new Chart();
            _chart.labels = uniqueMonths.ToArray();
            _chart.datasets = new List<Datasets>();
            List<Datasets> _dataSet = new List<Datasets>();
            foreach(var d in uniqueProducts)
            {
                var colors = new string[uniqueProducts.Count()];
                for (int j = 0; j < colors.Length; j++) colors[j] = cols[i];
                _dataSet.Add(new Datasets()
                {
                    label = d,
                    data = (from a in data where a.ProductName == d select a.Amount.Value).ToArray(),
                    backgroundColor = new string[] {cols[i]},
                    borderColor = new string[] {cols[i]},
                    borderWidth = "1"
                });
                i++;
            }
            _chart.datasets = _dataSet;
            return Json(_chart, JsonRequestBehavior.AllowGet);
        }


7. Index


<canvas id="MultiLineChart" width="400" height="100"></canvas>
<script>
    var c = document.getElementById("MultiLineChart");
    var ctx = c.getContext("2d");
    var tData = $.getValues("/Home/MultiLineChartData");
    var myLineChart = new Chart(ctx, {
        type: 'line',
        data: tData
    });
</script>

 

 

 

No comments:

Post a Comment