【发布时间】:2017-04-18 09:42:16
【问题描述】:
我尝试使用莫里斯面积图,我不知道如何正确序列化数据并发送莫里斯面积图可以理解的日期。
这是 HomeController 中从 DB 获取数据的方法。
public ActionResult GetData()
{
List<GraphData> GraphDataList = new List<GraphData>();
var user = db.Users.Where(p => p.Email == User.Identity.Name).Single();
var Requests = db.Transactions.Where(p => p.Package_id != null && p.User_id == user.Id);
DateTime day = new DateTime();
int CountPerDay = 0;
// count of request per day
foreach (var request in Requests)
{
if (day.Year == request.Date.Year && day.Day == request.Date.Day)
{
CountPerDay++;
}
else
{
// To 2016-12-03 format of date
string Date = day.Year + "-" + day.Month + "-" + day.Day;
GraphDataList.Add(new GraphData(Date, CountPerDay));
CountPerDay = 0;
day = request.Date;
}
}
// First elem in list is wrong
GraphDataList.RemoveAt(0);
return Json(GraphDataList, JsonRequestBehavior.AllowGet);
}
图形数据类
public class GraphData
{
public string label { get; set; }
public int value { get; set; }
public GraphData(string label, int value)
{
this.label = label;
this.value = value;
}
public GraphData()
{
}
}
html代码中的面积图
<div class="col-lg-6">
<div class="panel panel-default">
<div class="panel-heading">
Request statistic
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div id="area-example"></div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
和 func 从控制器获取数据并发送到 Morris.Area
<!--Get Data for Graph-->
<script type="text/javascript">
$(document).ready(function() {
$.get('@Url.Action("GetData","Home")', function (result) {
new Morris.Area({
// ID of the element in which to draw the chart.
element: 'area-example',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [result],
// The name of the data record attribute that contains x-values.
xkey: 'label',
ykeys: ['value'],
labels: ['Success requests'],
pointSize: 2,
hideHover: 'auto',
resize: true
});
});
});
</script>
但是如果像这样的初始化数据
<!--Get Data for Graph-->
<script type="text/javascript">
$(document).ready(function() {
$.get('@Url.Action("GetData","Home")', function (result) {
new Morris.Area({
// ID of the element in which to draw the chart.
element: 'area-example',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [
{ label: '2016-12-3', value: 150},
{ label: '2016-12-4', value: 221},
{ label: '2016-12-5', value: 43},
{ label: '2016-12-6', value: 21},
{ label: '2016-12-7', value: 312}
],
// The name of the data record attribute that contains x-values.
xkey: 'label',
ykeys: ['value'],
labels: ['Success requests'],
pointSize: 2,
hideHover: 'auto',
resize: true
});
});
});
</script>
【问题讨论】:
标签: javascript c# jquery asp.net-mvc morris.js