如何使用来自数据库C#的数据创建chartjs图表

问题描述 投票:-2回答:1

我正在尝试在.Net Core Web应用程序中使用来自数据库的数据创建chart.js图。我正在使用ajax来调用将从数据库中提取数据的方法,但是我不确定如何对数据进行分组以显示在图中。

目前,我有一个看起来像这样的数据库:

Database table

我希望显示最底部的时间,并计算成功完成多少工作以及有多少例外工作。目前,我的图形已经过硬编码。

Hard coded graph layout

// Area Chart Example
var ctx = document.getElementById("canvas")
var lineChartData = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
    label: 'Failed',
    borderColor: "MediumSeaGreen",
    backgroundColor: "MediumSeaGreen",
    fill: false,
    data: [
        30000, 30162, 26263, 18394, 18287, 28682, 31274, 33259, 25849, 
 24159, 32651, 31984, 38451
    ],
    yAxisID: 'y-axis-1',
}, {
    label: 'Exceptioned',
    borderColor: "Tomato",
    backgroundColor: "Tomato",
    fill: false,
    data: [
        20000, 30162, 26263, 33259, 18287, 28682, 25849, 18394, 25849, 
 24159, 32651, 31984, 38451
    ],
    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
                },
            }],
        }
    }
});
javascript c# sql asp.net-core chart.js
1个回答
0
投票

这里是一个简单的演示,如下所示:

1.Model:

public class Job
{
    public int JobId { get; set; }
    public string JobName { get; set; }
    public string JobStatus { get; set; }
    public DateTime JobCompletion { get; set; }
}

2。查看:

<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: '/Jobs/Index',
                  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();
        var ctx = document.getElementById("canvas")
        var lineChartData = {
            labels: simpleData[0].myDate, 
            datasets: [{
                label: 'Sucess',
                borderColor: "MediumSeaGreen",
                backgroundColor: "MediumSeaGreen",
                fill: false,
                data:   simpleData[0].mySuccess,
                yAxisID: 'y-axis-1',
            }, {
                label: 'Exceptioned',
                borderColor: "Tomato",
                backgroundColor: "Tomato",
                fill: false,
                data: simpleData[0].myException,
                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>
}

3.Controller:

public class JobsController : Controller
{
    private readonly YourContext _context;

    public JobsController(YourContext context)
    {
        _context = context;
    }

    // GET: Jobs
    public async Task<ActionResult> Index()
    {
        var date = await _context.Job.Select(j => j.JobCompletion).Distinct().ToListAsync();
        var success =_context.Job
            .Where(j => j.JobStatus == "Success")
            .GroupBy(j => j.JobCompletion)
            .Select(group=>new {
                JobCompletion = group.Key,
                Count=group.Count()
            });
        var countSuccess = success.Select(a => a.Count).ToArray();
        var exception = _context.Job
            .Where(j => j.JobStatus == "Exception")
            .GroupBy(j => j.JobCompletion)
            .Select(group => new {
                JobCompletion = group.Key,
                Count = group.Count()
            });
        var countException = exception.Select(a => a.Count).ToArray();
        return new JsonResult(new { myDate=date,mySuccess= countSuccess, myException= countException });
    }
}

4。数据库:

enter image description here

5。结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.