ChartJS 显示图表但 ASP net core 中没有数据
ChartJS shows chart but no data in ASP net core
我正在尝试将来自 API 请求的一些数据显示到 Chart JS 条形图中。
型号:
public class MachineApiModel
{
public string id { get; set; }
public Production[] productions { get; set; }
public string customerId { get; set; }
public string siteId { get; set; }
public string brand { get; set; }
public string type { get; set; }
public string serialNumber { get; set; }
public string line { get; set; }
public string ipAdres { get; set; }
public int port { get; set; }
public DateTime created { get; set; }
public DateTime changed { get; set; }
}
public class Production
{
public string id { get; set; }
public string machineId { get; set; }
public string purchaseOrder { get; set; }
public DateTime startTime { get; set; }
}
public class ProductionChartModel
{
[JsonProperty(PropertyName = "Brand")]
public List<string> Brand { get; set; }
[JsonProperty(PropertyName = "Port")]
public List<int> Port { get; set; }
}
控制器:(接收来自 API 调用的机器型号列表):
public async Task<List<MachineApiModel>> GetMachineApiAsync()
{
List<MachineApiModel> Machines = new List<MachineApiModel>();
HttpClient client = _api.Init();
HttpResponseMessage res = await client.GetAsync("Machine");
if (res.IsSuccessStatusCode)
{
try
{
var result = await res.Content.ReadAsStringAsync();
Machines = JsonConvert.DeserializeObject<List<MachineApiModel>>(result);
}
catch (Exception ex)
{
_logger.LogError(ex, $"Something went wrong");
}
}
return Machines;
}
Index.cshtml.cs:
我可以看到 JsonResult 是从模型数据中填充的。所以这是有效的。
private readonly MachineController _machineController = new();
private readonly ILogger<IndexModel> _logger;
[BindProperty]
public List<MachineApiModel> MachineApiModel { get; set; }
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public async Task<IActionResult> OnGet()
{
MachineApiModel = await _machineController.GetMachineApiAsync();
return Page();
}
public async Task<JsonResult> OnGetChartData()
{
MachineApiModel = await _machineController.GetMachineApiAsync();
var chartModel = new ProductionChartModel();
chartModel.Brand = new List<string>();
chartModel.Port = new List<int>();
foreach (var inv in MachineApiModel)
{
chartModel.Brand.Add(inv.brand);
chartModel.Port.Add(inv.port);
}
return new JsonResult(chartModel);
}
Index.cshtml:
图表绘制在页面上,但由于某种原因没有显示数据。这就是我卡住的地方。所以它基本上是一个空图表。
<p>Charts</p>
<div class="container">
<canvas id="chart" width="500" height="300"></canvas>
</div>
<script>
var myAmounts = [];
var myCategories = [];
var Machines;
function showChart() {
myAmounts = Machines.Port;
myCategories = Machines.Brand;
console.log(myAmounts);
console.log(myCategories);
let popCanvasName = document.getElementById("chart");
let barChartName = new Chart(popCanvasName, {
type: 'bar',
data: {
labels: myCategories,
datasets: [{
label: 'Machines',
data: myAmounts,
backgroundColor: [
'rgba(255, 99, 132, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(255, 206, 86, 0.6)',
'rgba(75, 192, 192, 0.6)',
'rgba(153, 102, 255, 0.6)',
]
}]
},
options: {
responsive: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
function getChartData() {
return fetch('./Index?handler=ChartData',
{
method: 'get',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
.then(function (response) {
if (response.ok) {
return response.text();
} else {
throw Error('Response Not OK');
}
})
.then(function (text) {
try {
return JSON.parse(text);
} catch (err) {
throw Error('Method Not Found');
}
})
.then(function (responseJSON) {
Machines = responseJSON;
showChart();
})
}
getChartData();
</script>
您可以添加 console.log(Machines)
以检查 Console
面板中的响应。然后你会发现响应中的属性名字是驼峰式.
更改以下代码:
function showChart() {
myAmounts = Machines.port;
myCategories = Machines.brand;
//.....
}
我正在尝试将来自 API 请求的一些数据显示到 Chart JS 条形图中。
型号:
public class MachineApiModel
{
public string id { get; set; }
public Production[] productions { get; set; }
public string customerId { get; set; }
public string siteId { get; set; }
public string brand { get; set; }
public string type { get; set; }
public string serialNumber { get; set; }
public string line { get; set; }
public string ipAdres { get; set; }
public int port { get; set; }
public DateTime created { get; set; }
public DateTime changed { get; set; }
}
public class Production
{
public string id { get; set; }
public string machineId { get; set; }
public string purchaseOrder { get; set; }
public DateTime startTime { get; set; }
}
public class ProductionChartModel
{
[JsonProperty(PropertyName = "Brand")]
public List<string> Brand { get; set; }
[JsonProperty(PropertyName = "Port")]
public List<int> Port { get; set; }
}
控制器:(接收来自 API 调用的机器型号列表):
public async Task<List<MachineApiModel>> GetMachineApiAsync()
{
List<MachineApiModel> Machines = new List<MachineApiModel>();
HttpClient client = _api.Init();
HttpResponseMessage res = await client.GetAsync("Machine");
if (res.IsSuccessStatusCode)
{
try
{
var result = await res.Content.ReadAsStringAsync();
Machines = JsonConvert.DeserializeObject<List<MachineApiModel>>(result);
}
catch (Exception ex)
{
_logger.LogError(ex, $"Something went wrong");
}
}
return Machines;
}
Index.cshtml.cs: 我可以看到 JsonResult 是从模型数据中填充的。所以这是有效的。
private readonly MachineController _machineController = new();
private readonly ILogger<IndexModel> _logger;
[BindProperty]
public List<MachineApiModel> MachineApiModel { get; set; }
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public async Task<IActionResult> OnGet()
{
MachineApiModel = await _machineController.GetMachineApiAsync();
return Page();
}
public async Task<JsonResult> OnGetChartData()
{
MachineApiModel = await _machineController.GetMachineApiAsync();
var chartModel = new ProductionChartModel();
chartModel.Brand = new List<string>();
chartModel.Port = new List<int>();
foreach (var inv in MachineApiModel)
{
chartModel.Brand.Add(inv.brand);
chartModel.Port.Add(inv.port);
}
return new JsonResult(chartModel);
}
Index.cshtml: 图表绘制在页面上,但由于某种原因没有显示数据。这就是我卡住的地方。所以它基本上是一个空图表。
<p>Charts</p>
<div class="container">
<canvas id="chart" width="500" height="300"></canvas>
</div>
<script>
var myAmounts = [];
var myCategories = [];
var Machines;
function showChart() {
myAmounts = Machines.Port;
myCategories = Machines.Brand;
console.log(myAmounts);
console.log(myCategories);
let popCanvasName = document.getElementById("chart");
let barChartName = new Chart(popCanvasName, {
type: 'bar',
data: {
labels: myCategories,
datasets: [{
label: 'Machines',
data: myAmounts,
backgroundColor: [
'rgba(255, 99, 132, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(255, 206, 86, 0.6)',
'rgba(75, 192, 192, 0.6)',
'rgba(153, 102, 255, 0.6)',
]
}]
},
options: {
responsive: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
function getChartData() {
return fetch('./Index?handler=ChartData',
{
method: 'get',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
.then(function (response) {
if (response.ok) {
return response.text();
} else {
throw Error('Response Not OK');
}
})
.then(function (text) {
try {
return JSON.parse(text);
} catch (err) {
throw Error('Method Not Found');
}
})
.then(function (responseJSON) {
Machines = responseJSON;
showChart();
})
}
getChartData();
</script>
您可以添加 console.log(Machines)
以检查 Console
面板中的响应。然后你会发现响应中的属性名字是驼峰式.
更改以下代码:
function showChart() {
myAmounts = Machines.port;
myCategories = Machines.brand;
//.....
}