我正在尝试在我的asp.net视图中加载chart.js折线图,但该视图仅显示json数据。
页面甚至没有显示布局页面,只显示从控制器返回的json数据。
下面是我的视图,控制器和json返回。
我的观点
@{
ViewBag.Title = "LoadLineChart";
}
<h2>LoadLineChart</h2>
<div>
<label>Multi Bar Chart</label>
<canvas id="LineChart" width="400" height="150"></canvas>
</div>
<script src="~/Scripts/Chart.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/Home/LoadLineChart",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var c = document.getElementById("LineChart");
var ctx = c.getContext("2d");
var myBarChart = new Chart(ctx, {
type: 'line',
data: data
});
},
error: function () {
alert('some thing wrong try again...')
}
});
});
</script>
我的控制器
public JsonResult LoadLineChart()
{
string[] chartcolors = {
"rgb(255, 99, 132)",//red
"rgb(54, 162, 235)",//blue
"rgb(153, 102, 255)",//purple
"rgb(255, 159, 64)",//orange
"rgb(255, 205, 86)",//yellow
"rgb(75, 192, 192)",//green
"rgb(231,233,237)"//grey
};
ChartData cd = new ChartData();
DataTable dat = cd.GetSIMCardData();
Chart _chart = new Chart();
_chart.labels = dat.AsEnumerable().Select(r => r.Field<string>("month") + "-" + r.Field<string>("year")).ToArray();
_chart.datasets = new List<Datasets>();
List<Datasets> _dataSet = new List<Datasets>();
for (int i = 0; i < 4; i++)
{
var bgcolor = Enumerable.Repeat(chartcolors[i], dat.Rows.Count).ToArray();
_dataSet.Add(new Datasets()
{
label = dat.Columns[i].ColumnName,
data = dat.AsEnumerable().Select(r => r.Field<int>(dat.Columns[i])).ToArray(),
backgroundColor = bgcolor,
borderColor = bgcolor,
borderWidth = "1"
});
_chart.datasets = _dataSet;
}
return Json(_chart, JsonRequestBehavior.AllowGet);
}
//在视图中显示的json数据
{"labels":["November-2016","December-2016","January-2017","February-
2017","March-2017","April-2017","May-2017","June-2017","July-2017","August-
2017","September-2017","October-2017"],
"datasets":[{"label":"NormalSim",
"backgroundColor":["rgb(255, 99, 132)","rgb(255, 99, 132)","rgb(255, 99,
132)","rgb(255, 99, 132)","rgb(255, 99, 132)","rgb(255, 99, 132)","rgb(255,
99, 132)","rgb(255, 99, 132)","rgb(255, 99, 132)","rgb(255, 99,
132)","rgb(255, 99, 132)","rgb(255, 99, 132)"],"borderColor":["rgb(255, 99,
132)","rgb(255, 99, 132)","rgb(255, 99, 132)","rgb(255, 99, 132)","rgb(255,
99, 132)","rgb(255, 99, 132)","rgb(255, 99, 132)","rgb(255, 99,
132)","rgb(255, 99, 132)","rgb(255, 99, 132)","rgb(255, 99, 132)","rgb(255,
99, 132)"],
"borderWidth":"1",
"data": [10702400,10456635,10236438,10037215,10051764,9877641,9642252,
9519984,9360297, 9337899,9229813,9202321]}]}