Im trying to display some data comming from API request into a Chart JS bar chart.
Model:
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; }
}
Controller: (Recieving list of machine model comming from API call):
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: I can see that the JsonResult is filled from the model data. So this is working.
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: The chart is drawn on the page but the data is not displayed for some reason. This is where i get stuck. So its basically a empty chart.
<p>Charts</p>
<div >
<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>
CodePudding user response:
You could add console.log(Machines)
to check the response in Console
panel. Then you will find the property name in response is camel case.
Change your code below:
function showChart() {
myAmounts = Machines.port;
myCategories = Machines.brand;
//.....
}