我试图使用饼图来显示统计数据。数据在我的表格中,我这样得到:
public class StatisticsAccess
{
public static object getTypesForStatistics()
{
var dbo = new UsersContext();
var all = (from a in dbo.Note
select a).ToList();
var results = all.GroupBy(item => item.language.lang)
.Select(g => new
{
language = g.Key,
Count = g.Count()
});
return (results.ToList());
}
}
控制器:
public class StatisticsController : Controller
{
//
// GET: /Statistics/
public ActionResult Index()
{
return View();
}
public void displayChart()
{
var results = Json(DAL.StatisticsAccess.getTypesForStatistics());
}
}
查看:
@(Html.Kendo().Chart()
.Name("chart")
.Title(title => title
.Text("Share of Internet Population Growth, 2007 - 2012")
.Position(ChartTitlePosition.Bottom))
.Legend(legend => legend
.Visible(false)
)
.Series(series =>
{
series.Column("Count").CategoryField("language");
})
.DataSource(ds => ds.Read(read => read.Action("displayChart", "Statistics")))
.Tooltip(tooltip => tooltip
.Visible(true)
.Format("{0}%")
)
)
我的视图中没有语法错误,但是当我加载页面时,我的图表只显示为空。
任何人都可以向我解释我应该遵循的语法来修复此错误吗? THX
答案 0 :(得分:1)
您的代码至少存在两个主要问题。
您已经定义了一个柱形图,这应该是一个饼图:
@(Html.Kendo().Chart<MyModel>()
.Name("chart")
.Title(title => title
.Text("Share of Internet Population Growth, 2007 - 2012")
.Position(ChartTitlePosition.Bottom))
.Legend(legend => legend.Visible(false))
.Series(series => {
series.Pie(model => model.language, model => model.Count);
})
.DataSource(ds => ds.Read(read => read.Action("displayChart", "Statistics")))
.Tooltip(tooltip => tooltip
.Visible(true)
.Format("{0}%")
)
)
您的操作返回无效,而不是ActionResult
:
public class StatisticsController : Controller
{
[HttpPost]
public ActionResult displayChart()
{
var results = DAL.StatisticsAccess.getTypesForStatistics();
return Json(results);
}
}
此外,您可能希望这样做:
创建视图模型:
public class PieModel {
public string Language { get;set; }
public int Count { get;set; }
}
将模型添加到图表中。
@(Html.Kendo().Chart<PieModel>() {
...
更改您的查询:
public IEnumerable<PieModel> getTypesForStatistics()
{
var dbo = new UsersContext();
var all = (from a in dbo.Note
select a).ToList();
var results = all.GroupBy(item => item.language.lang)
.Select(g => new PieModel
{
Language = g.Key,
Count = g.Count()
});
return results.ToList();
}