Reputation: 65
I am trying to implement chartJS with ASP .NET Core MVC. I've been trying to make chart that displays data from database (following this tutorial). I have a table "WorkTS" and I need to display data from the following columns: hrPlan, hrFact and hrSub for the year 2021 (Datetime stored in dtMonth column). I'm not getting any error messages, but all I get is a blank space in place of a chart. Here's my code:
Model:
public class WorkTS
{
public string? org { get; set; }
public DateTime? dt { get; set; }
public decimal? hrFact { get; set; }
public decimal? hrPlan { get; set; }
public decimal? hrReestr { get; set; }
public DateTime? dtSynchro { get; set; }
public DateTime? dtMonth { get; set; }
public decimal? hrSub { get; set; }
public decimal? hrFactWSub { get; set; }
}
Controller:
public HomeController(ILogger<HomeController> logger, AzureDBContext azcontext)
{
_logger = logger;
_azdb = azcontext;
}
public async Task<ActionResult> OnGetWorkTSData()
{
var month = _azdb.WorkTs.Select(w => w.dtMonth).Distinct().ToArray();
var plan = _azdb.WorkTs.Select(w => w.hrPlan).Distinct().ToArray();
var sub = _azdb.WorkTs.Select(w => w.hrSub).Distinct().ToArray();
var fact = _azdb.WorkTs.Select(w => w.hrFact).Distinct().ToArray();
return new JsonResult(new { dtMonth = month, hrPlan = plan, hrSub = sub, hrFact = fact });
}
View:
<div>
<canvas id="workTSChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
function GetJSON_Simple_workTS() {
var resp = [];
$.ajax({
type: "GET",
url: '@Url.Action("OnGetWorkTSData","home")',
contentType: "application/json;",
dataType: "json",
success: function (data) {
resp.push(data);
},
error: function (req, status, error) {
alert("error");
},
return resp;
}
}
var simpleData = GetJSON_Simple_workTS();
const config = {
type: 'bar',
data: {
labels: [
'ООО МТК',
],
datasets: [{
label: 'Plan hours',
backgroundColor: 'rgb(161, 221, 239)',
borderColor: 'rgb(161, 221, 239)',
data: simpleData[0].hrPlan,
},
{
label: 'Sub hours',
backgroundColor: 'rgb(254, 171, 133)',
borderColor: 'rgb(254, 171, 133)',
data: simpleData[0].hrSub,
},
{
label: 'Fact hours',
backgroundColor: 'rgb(127, 137, 138)',
borderColor: 'rgb(127, 137, 138)',
data: simpleData[0].hrFact,
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'WorkTS Chart'
}
}
},
};
var wotkTSchart = new Chart(
document.getElementById('workTSChart'),
config
);
</script>
Upvotes: 0
Views: 446
Reputation: 4839
Your function GetJSON_Simple_workTS
is broken, it's missing a )
and it has return resp;
as part of the $.ajax
request options.
The $.ajax
success
callback gets called asynchronously, therefore if you're not familiar with async
and promises
, I would suggest putting your chart creation code in a function and calling that in the success
callback, otherwise your GetJSON_Simple_workTS
function will return an empty array as it hasn't waited for the response to come back.
Upvotes: 1