[我正在尝试使用带有MCV的Google图表显示一个简单的饼图,并在阅读了无数教程之后,我不确定为什么我仍然会出现空白屏幕。
如果遵循本教程,则会加载https://developers.google.com/chart/interactive/docs/gallery/piechart饼图,但是当我尝试从数据库发送数据时,总是会出现空白屏幕
使用实体框架
public partial class DividendTracking
{
public int ID { get; set; }
public Nullable<System.DateTime> Date { get; set; }
public string Product { get; set; }
public Nullable<double> Shares { get; set; }
public Nullable<double> SharePrice { get; set; }
public string Description { get; set; }
public string Currency { get; set; }
public Nullable<double> amount { get; set; }
}
我的Contoller看起来像这样
public ActionResult Index()
{
HomelabEntities enties = new HomelabEntities();
var result = enties.DividendTrackings.Where(x => x.Product != null).GroupBy(o => o.Product)
.Select(g => new { product = g.Key, total = g.Sum(i => i.Shares) }).ToList();
//return View(result);
// return View((Json(result, JsonRequestBehavior.AllowGet)));
return View(new JsonResult { Data = result, JsonRequestBehavior = JsonRequestBehavior.AllowGet });
}
最后我的观点看起来像这样
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'product');
data.addColumn('number', 'amount');
// don't forget to add JQuery in your view.
$.getJSON("@Url.Action("/Home/Index")", null, function (result) {
$.each(result, function (i, item) {
data.addRow([item.product, item.amount]);
});
var options = {
title: 'Shares',
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
</script>
<div id="chartdiv" style="width: 500px; height: 300px;"></div>
我不确定为什么图表显示为空白
我刚刚添加了result.results的这段代码。你能试试这个吗?您也可以使用consol.log(result);进行检查。您所得到的方法。
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'product');
data.addColumn('number', 'amount');
// don't forget to add JQuery in your view.
$.getJSON("@Url.Action("/Home/Index")", null, function (result) {
$.each(result.results, function (i, item) {
data.addRow([item.product, item.amount]);
});
var options = {
title: 'Shares',
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
</script>
<div id="chartdiv" style="width: 500px; height: 300px;"></div>