[英]Chart.js - Getting data from database using sql server and asp.net mvc5
I displayed and styled the chart.js and am also using mock data in the array, I just can't get my head around how to populate the data in the chart.js using MVC 5. I have tried lots of different methods and it's displaying data but not displaying the chart.我显示并设置了 chart.js 的样式,并且还在数组中使用了模拟数据,但我无法理解如何使用 MVC 5 在 chart.js 中填充数据。我尝试了很多不同的方法,它是显示数据但不显示图表。 Ideally, I need two datasets;
理想情况下,我需要两个数据集; one is for the weekly expense and one for the monthly expense.
一个是每周费用,一个是每月费用。 Here are the methods I have tried.
以下是我尝试过的方法。 If anyone can suggest what I am doing wrong or just point me in the right direction it would be much appreciated.
如果有人可以建议我做错了什么,或者只是指出我正确的方向,那将不胜感激。
Thank you.谢谢你。
ChartController图表控制器
public JsonResult WeeklyExpenseSummary()
{
System.Web.UI.DataVisualization.Charting.Chart chart = new System.Web.UI.DataVisualization.Charting.Chart();
DateTime d = DateTime.Today;
var offset = d.DayOfWeek - System.DayOfWeek.Monday;
offset = (offset < 0) ? 6 : offset;
DateTime FromDate = d.AddDays(-offset);
DateTime ToDate = FromDate.AddDays(7);
var data = (from a in ExpenseReport
join at in Amount on a.ItemName equals at.Amount
where a.Date >= FromDate
&& a.Date < ToDate
group at by at.ItemName into g
select new
{
value = g.Count(),
label = g.Key
}).ToList();
return Json(JsonConvert.SerializeObject(chart.barChart(data)), JsonRequestBehavior.AllowGet);
}
public JsonResult MonthlyExpenseSummary()
{
System.Web.UI.DataVisualization.Charting.Chart chart = new System.Web.UI.DataVisualization.Charting.Chart();
DateTime today = DateTime.Today;
DateTime startDate = new DateTime(today.Year, today.Month, 1);
DateTime endDate = new DateTime(today.Year, today.Month, DateTime.DaysInMonth(today.Year, today.Month));
var data = (from a in ExpenseReport
join at in Amount on a.itemName equals at.Amount
where a.Date >= FromDate
&& a.Date < ToDate
group at by at.ItemName into g
select new
{
value = g.Count(),
label = g.Key
}).ToList();
return Json(JsonConvert.SerializeObject(chart.barChart(data)), JsonRequestBehavior.AllowGet);
}
Index.cshtml索引.cshtml
<div style="width: 80%;">
<canvas id="barChart" heigh="400" width="400"></canvas>
</div>
<script>
var chart = document.getElementById("barChart").getContext('2d');
Chart.defaults.global.animation.duration = 2000;
var barChart = new Chart(chart,
{
type: 'bar',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets: [{
label: 'Weekly Expenses',
fill: true,
barTension: 0.1,
borderColor: '#2C3E50',
borderWidth: 2,
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "#2C3E50",
pointBackgroundColor: "#fff",
pointBorderWidth: 2,
pointHoverRadius: 8,
pointHoverBackgroundColor: "#2C3E50",
pointHoverBorderColor: "#2C3E50",
pointHoverBorderWidth: 5,
pointRadius: 10,
PointHitRadius:10,
data: [20,30,40,50,60,70,80,90,100,120,140,50]
},
{
label: 'Monthly Expenses',
fill: true,
barTension: 0.8,
backgroundColor: '#2C3E50',
borderColor: '#f0c419',
borderWidth: 2,
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "#f0c419",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "#f0c419",
pointHoverBorderColor: "#f0c419",
pointHoverBorderWidth: 2,
pointRadius: 1,
PointHitRadius:1,
data: /*[10,20,30,40,50,60,70,80,90,100,110,120]*/ data
}
]
},
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
}]
}
}
});
</script>
A few months ago when i was in a project, i did smth like this.几个月前,当我在做一个项目时,我做了这样的事情。 We had a calendar on website.
我们在网站上有一个日历。 When the date changes we refresh charts by using ajax.
当日期更改时,我们使用 ajax 刷新图表。
First, Use ViewModel, then on your Index.cshtml render partialview with Model.首先,使用 ViewModel,然后在您的 Index.cshtml 上使用 Model 渲染 partialview。 Secondly, send ajax request to grab data from service.
其次,发送ajax请求从服务中抓取数据。 OnSuccess Method fill the id of div with data.
OnSuccess 方法用数据填充 div 的 id。
On your Controller return PartialView with Model.在您的控制器上返回带有模型的 PartialView。
On your partialview, create empty array to store data.在您的局部视图上,创建空数组来存储数据。 then fill the array from Model then use it on chart.
然后从模型填充数组,然后在图表上使用它。
try this.尝试这个。
Code Of Index.cshtml索引代码.cshtml
@model ProjectName.Models.MyViewModel
<div id="DataZone">
@{
Html.RenderPartial("your_partialview",Model);
}
</div>
<script>
..
$.ajax({
url: "request_url",
method: "post",
data: {
param1: yourval,
param2: yourval2
},
success: function (data) {
$("#dataZone").html(data);
},
error: function(data) {
console.log(data);
}
});
});
<script>
ex Code of Controller前控制人代码
[HttpPost]
public ActionResult GetData(DateTime param1,DateTime param2)
{
ExampleService es= new ExampleService ();
ExampleViewModel evm = new ExampleViewModel ();
evm.ListForChart = es.GetWeekly(param1,param2);
evm.ListForChart2 = es.GetMothly(param1,param2);
..
return PartialView("your_partialviewname", evm);
}
ex code of ExampleViewModel ExampleViewModel 的前代码
public class MarketViewModel
{
public List<YourModel> ListForChart { get; set; }
public List<YourModel> ListForChart2 { get; get;}
}
example Service from your code:
public class YourService{
private List<YourModel> exampleList;
public YourService(){
exampleList = new List<YourModel>();
}
public List<YourModel> GetWeekly(param1, param2)
// data is List of your model. return this.
var data = (from a in ExpenseReport
join at in Amount on a.ItemName equals at.Amount
where a.Date >= FromDate
&& a.Date < ToDate
group at by at.ItemName into g
select new
{
value = g.Count(),
label = g.Key
}).ToList();
return data;
}
}
example code of PartialView PartialView 的示例代码
<div id="chart-gonna-be-here"></div>
<script type="text/javascript">
$(document).ready(function() {
CreateChart();
}
CreateChart = function(){
var data= []; // You will fill data from Model.
@foreach (var item in Model.ListForChart.OrderBy(c => c.Date))
{
@:data.push(@item.YourModelObj.ToString();
}
}
// Then Create chart // 然后创建图表
var chart = document.getElementById("barChart").getContext('2d');
Chart.defaults.global.animation.duration = 2000;
var barChart = new Chart(chart,
{
type: 'bar',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets: [{
label: 'Weekly Expenses',
fill: true,
barTension: 0.1,
borderColor: '#2C3E50',
borderWidth: 2,
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "#2C3E50",
pointBackgroundColor: "#fff",
pointBorderWidth: 2,
pointHoverRadius: 8,
pointHoverBackgroundColor: "#2C3E50",
pointHoverBorderColor: "#2C3E50",
pointHoverBorderWidth: 5,
pointRadius: 10,
PointHitRadius:10,
data: [20,30,40,50,60,70,80,90,100,120,140,50]
},
{
label: 'Monthly Expenses',
fill: true,
barTension: 0.8,
backgroundColor: '#2C3E50',
borderColor: '#f0c419',
borderWidth: 2,
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "#f0c419",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "#f0c419",
pointHoverBorderColor: "#f0c419",
pointHoverBorderWidth: 2,
pointRadius: 1,
PointHitRadius:1,
data: /**/ data <<--- data will be here
}
]
},
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
}]
}
}
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.