How to make a chart linked to the C# database?

0👍

Here is a whole working demo you could follow:

Model:

public class VoyageVM
{
    public DateTime DateEnregistrement { get; set; }
    public bool VoyageEffectuer { get; set; }
    public bool VoyageAnnuler { get; set; }
}

View:

<canvas id="canvas" width="400" height="400"></canvas>
@section Scripts{
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js" integrity="sha256-qSIshlknROr4J8GMHRlW3fGKrPki733tLq+qeMCR05Q=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js" integrity="sha256-xKeoJ50pzbUGkpQxDYHD7o7hxe0LaOGeguUidbq6vis=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.css" integrity="sha256-IvM9nJf/b5l2RoebiFno92E5ONttVyaEEsdemDC6iQA=" crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js" integrity="sha256-arMsf+3JJK2LoTGqxfnuJPFTU4hAK57MtIPdFpiHXOU=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" integrity="sha256-aa0xaJgmK/X74WM224KMQeNQC2xYKwlAt08oZqjeF0E=" crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" integrity="sha256-Uv9BNBucvCPipKQ2NS9wYpJmi8DTOEfTA/nH2aoJALw=" crossorigin="anonymous"></script>
    <script>
        function GetJSON_Simple() {
            var resp = [];
            $.ajax({
                type: "GET",
                url: '/Home/GetJson',
                async: false,
                contentType: "application/json",
                success: function (data) {
                    resp.push(data);
                },
                error: function (req, status, error) {
                    // do something with error
                    alert("error");
                }
            });
            return resp;
        }
        var simpleData = GetJSON_Simple();
        console.log(simpleData)
        var ctx = document.getElementById("canvas")
        var lineChartData = {
            labels: simpleData[0].myDate,
            datasets: [{
                label: 'VoyageEffectuer',
                borderColor: "MediumSeaGreen",
                backgroundColor: "MediumSeaGreen",
                fill: false,
                data: simpleData[0].myEffectuer,
                yAxisID: 'y-axis-1'
            },
            {
                label: 'VoyageAnnuler',
                borderColor: "Tomato",
                backgroundColor: "Tomato",
                fill: false,
                data: simpleData[0].myAnnuler,
                yAxisID: 'y-axis-2'
            }]
        };

    window.myLine = Chart.Line(ctx, {
            data: lineChartData,
            options: {
            responsive: true,
            hoverMode: 'index',
            stacked: false,
            title: {
                display: true,
                text: 'Processes'
            },
            scales: {
                yAxes: [{
                type: 'linear',
                    display: true,
                    position: 'left',
                    id: 'y-axis-1',
                }, {
                type: 'linear',
                    display: true,
                    position: 'right',
                    id: 'y-axis-2',

                    // grid line settings
                    gridLines: {
                drawOnChartArea: false, // only want the grid lines for one axis to show up
                    },
                }],
            }
        }
    });
    </script>
}

Controller:

public class HomeController : Controller
{
    private readonly YourDbContext ctx;
    public HomeController(YourDbContext ctx)
    {
        this.ctx = ctx;
    }
    public async Task<ActionResult> GetJson()
    {
        var data = ctx.VoyageVM.ToList();
        var date = data.Select(a => a.DateEnregistrement.Month)
                    .Distinct()
                    .OrderBy(a => a).ToArray();
        var Effectuer = (from t in data
                        where t.VoyageEffectuer==true
                        group t by new { Month = t.DateEnregistrement.Month } into g
                        select new
                        {
                            Amount = g.Count(),
                            Month = g.Key.Month
                        }).ToList();
        var myEff = Effectuer.OrderBy(a =>a.Month)
                        .Select(a => a.Amount)
                        .ToList();
        var Annuler = (from t in data
                    where t.VoyageAnnuler == true
                    group t by new { Month = t.DateEnregistrement.Month } into g
                    select new
                    {
                        Amount = g.Count(),
                        Month = g.Key.Month
                    }).ToList();
        var myAnnu = Annuler.OrderBy(a => a.Month)
                        .Select(a => a.Amount)
                        .ToList();
        return new JsonResult(new { myDate = date, myEffectuer = myEff, myAnnuler = myAnnu });
    }
}

DbContext:

public class YourDbContext: DbContext
{
    public YourDbContext(DbContextOptions<YourDbContext> options)
        : base(options)
    {
    }
    public DbSet<VoyageVM> VoyageVM { get; set; }


    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<VoyageVM>().HasNoKey();
    }
}

👍:0

ChartJSCore is a library which would simplify this by quite a bit.

You’d basically build the chart up in your controller, and add it to your ViewData. Then you can use @Html.Raw(CreateChartCode("chart")) to render the appropriate javascript code, targeting the canvas with the id you give it ("chart" in this case).

A more detailed example is available in the GitHub repository’s readme.

Leave a comment