Kendo UI Column Chart数据绑定失效 求排查解决
MVC中Kendo柱状图无数据显示问题排查与解决
现有数据
| Type | Percentage | Date | Color |
|---|---|---|---|
| A | 25.5 | 2/12 | #2456C7 |
| B | 70 | 2/13 | #2456C8 |
| B | 50 | 2/14 | #2456C8 |
| B | 55.5 | 2/15 | #2456C8 |
| A | 60.3 | 2/13 | #2456C8 |
需求与问题
需要创建按Date分类、依Type显示多列的柱状图,但编写如下代码后图表空白无数据显示,需排查代码逻辑问题并给出解决方法。
原代码
@(Html.Kendo().Chart<EntitiesA.Report>() .Name("Report") .Title("ReportA") .Legend(legend => legend.Position(ChartLegendPosition.Top)) .DataSource(dataSource => dataSource .Read(read => read.Action("MethodReport", "ReportController")) .Group(group => group.Add(model => model.Type)) .Sort(sort => sort.Add(model => model.Date).Ascending()) ) .Series(series => { series.Column(model => model.Percentage) .Name("#= group.value # (Percentage)").CategoryField("Date").ColorField("Color"); }) .Legend(legend => legend.Position(ChartLegendPosition.Bottom)) .CategoryAxis(axis => axis.Labels(labels => labels.Format("MM/DD"))) .ValueAxis(axis => axis.Numeric() .Labels(labels => labels.Format("{0:N0}")) .MajorUnit(20) .Max(100) .Line(line => line.Visible(false)) ) .Tooltip(tooltip => tooltip.Visible(true).Format("{0:N0}")) )
问题排查
- 分组后分类字段配置错误:对
Type分组后,Kendo Chart的分类字段不能在Series中设置,需在CategoryAxis中指定,否则无法正确映射分组后的数据源结构。 - 日期格式与类型不匹配:后端返回的
Date为字符串格式,而分类轴设置了MM/DD格式,若未将字符串解析为DateTime类型,图表无法识别分类轴数据。 - 重复Legend配置:代码中两次调用
.Legend(),后一次会覆盖前一次配置,属于冗余代码。 - ColorField使用场景问题:分组模式下,若同一分组内存在不同颜色值,会导致渲染异常,需确保分组与颜色对应逻辑一致。
解决方法
修改后的完整代码
@(Html.Kendo().Chart<EntitiesA.Report>() .Name("Report") .Title("ReportA") .Legend(legend => legend.Position(ChartLegendPosition.Bottom)) .DataSource(dataSource => dataSource .Read(read => read.Action("MethodReport", "ReportController")) .Group(group => group.Add(model => model.Type)) .Sort(sort => sort.Add(model => model.Date).Ascending()) // 若后端返回Date为字符串,需添加Schema解析 .Schema(schema => schema .Model(model => model .Field("Date", typeof(DateTime)).Parse("parseDate") ) ) ) .Series(series => { series.Column(model => model.Percentage) .Name("#= group.value # (Percentage)") .ColorField("Color"); // 移除Series中的CategoryField }) .CategoryAxis(axis => axis .Field("Date") // 在分类轴中指定日期字段 .Labels(labels => labels.Format("MM/dd"))) // Kendo格式区分大小写,小写dd表示两位数日期 .ValueAxis(axis => axis.Numeric() .Labels(labels => labels.Format("{0:N0}")) .MajorUnit(20) .Max(100) .Line(line => line.Visible(false)) ) .Tooltip(tooltip => tooltip.Visible(true).Format("{0:N1}")) // 保留一位小数匹配数据精度 )
额外处理(若后端返回Date为字符串)
在页面添加日期解析JS函数:
function parseDate(dateString) { return kendo.parseDate(dateString, "M/dd"); }
内容的提问来源于stack exchange,提问作者Sri K
相关产品推荐
相关产品推荐

