I have a JSON data from database like below to build a dashboard in dashboard ASP.NET MVC. I would like to draw a daily and monthly bar chart with x-axis as datetime (Day) and y-axis as count of activities in a day.
JSON Data:
[{"count":42,"datetime":"2020-07-18T00:00:00"},{"count":49,"datetime":"2020-07-16T00:00:00"},{"count":90,"datetime":"2020-07-14T00:00:00"},{"count":85,"datetime":"2020-07-17T00:00:00"},{"count":100,"datetime":"2020-07-13T00:00:00"},{"count":38,"datetime":"2020-07-19T00:00:00"},{"count":53,"datetime":"2020-07-15T00:00:00"}]
and i want something like this
I've tried the following javascript code but can't. JSON data obtained from ViewBag.dataItems
<script type="text/javascript" >
window.onload = function () {
var result = @Html.Raw(ViewBag.dataItems);
var DataItem =[];
for (var i = 0; i < result.length; i++){
DataItem.push({
x: new Date(result[i].datetime),
y: result[i].count
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
data: [{
type: "column",
DataItem: DataItem
}]
});
chart.render();
};
</script>
ThankYou
As I referred to some samples from https://canvasjs.com/docs/charts/chart-types/html5-column-chart/ , they used dataPoints property instead of DataItem.
Here is a sample following your data. Hope to help, my friend:))
1. Controllers
public ActionResult Add()
{
ViewData["data"] = @"[{'count':42,'datetime':'2020-07-18T00:00:00'},{'count':49,'datetime':'2020-07-16T00:00:00'},{'count':90,'datetime':'2020-07-14T00:00:00'},{'count':85,'datetime':'2020-07-17T00:00:00'},{'count':100,'datetime':'2020-07-13T00:00:00'},{'count':38,'datetime':'2020-07-19T00:00:00'},{'count':53,'datetime':'2020-07-15T00:00:00'}]";
return View();
}
2. Views
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var result = @Html.Raw(ViewData["data"]);
this.console.log(result);
var DataItem = [];
for (var i = 0; i < result.length; i++) {
DataItem.push({
x: new Date(result[i].datetime),
y: result[i].count
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title: {
text: "Date Time Formatting"
},
data: [{
type: "column",
dataPoints: DataItem
}]
});
chart.render();
}
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.