我正在尝试使用chart.js生成图形。为了绘制图形,我正在使用模型,并通过控制器发送数据。我收到以下错误:
chartjs.init.js:3 Uncaught TypeError: Cannot read property 'getContext' of null at HTMLDocument.<anonymous> (chartjs.init.js:3) at f (jquery.js:1026) at Object.fireWith [as resolveWith] (jquery.js:1138) at Function.ready (jquery.js:427) at HTMLDocument.xt (jquery.js:97) (anonymous) @ chartjs.init.js:3 f @ jquery.js:1026 fireWith @ jquery.js:1138 ready @ jquery.js:427 xt @ jquery.js:97
我阅读了其他可用答案,所有答案都指向在脚本之前呈现图表的问题。但是尝试了所有解决方案并最终出现相同的错误。需要帮助。
在使用逻辑方面也需要帮助。
控制器:
public JsonResult BarChart()
{
List<DatapointLine> dataPoints = new List<DatapointLine>{
new DatapointLine(10, 30),
new DatapointLine(20, 40),
new DatapointLine(30, 50),
new DatapointLine(40, 60),
new DatapointLine(50, 0),
};
ViewBag.DataPoints = JsonConvert.SerializeObject(dataPoints);
return Json(dataPoints, JsonRequestBehavior.AllowGet);
}
型号:
public class DatapointLine
{
public DatapointLine(double x, double y)
{
this.X = x;
this.Y = y;
}
// setting the name to be used when serializing to JSON.
[DataMember(Name = "x")]
public Nullable<double> X = null;
//setting the name to be used whenserializing to JSON.
[DataMember(Name = "y")]
public Nullable<double> Y = null;
}
查看:
@{
Layout = null;
}
<html>
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
</head>
<body>
<div class="row">
<canvas id="myChart"></canvas>
</div>
</body>
</html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<!-- Chart JS -->
<script src="@Url.Content("~/Content/plugins/bower_components/Chart.js/chartjs.init.js")"></script>
<script src="@Url.Content("~/Content/plugins/bower_components/Chart.js/Chart.min.js")"></script>
<script type="text/javascript">
$(function() {
var data = getData();
AutoFollow(data);
});
function getData() {
var dateValue = [];
var countValue = [];
$.ajax({
url: "/Supernethome/BarChart",
dataType: 'json',
async: false
}).done(function(data) {
data.forEach(function(obj) {
dateValue.push(obj.X);
countValue.push(obj.Y);
});
});
return {
dateValue: dateValue,
countValue: countValue
};
}
function AutoFollow(data) {
var ctx = this.find("#myChart").getContext('2d');
var myChart = new Chart(ctx,
{
type: 'bar',
data: {
labels: data.dateValue, // here i want to show my date value
datasets: [
{
label: 'AutoFollow',
data: data.countValue, // here show my total count date wise
backgroundColor: "rgba(153,255,51,1)"
}
]
}
});
}
</script>
@*<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>*@
请提出陷阱,并提出更好的方法。 多谢一会:)