【发布时间】:2014-04-20 06:26:31
【问题描述】:
我正在尝试在 Google 图表中显示一些数据,但出现此错误:
Data column(s) for axis #0 cannot be of type string..
我有这个类的两个属性:
public class GAStatistics
{
public string Date { get; set; }
public string Visitors { get; set; }
}
我从这个控制器传递了这些属性的列表:
public class GAStatisticsController : Controller
{
//GET: /ShopStatistics/
public ActionResult GetData()
{
return Json(CreateCompaniesList(), JsonRequestBehavior.AllowGet);
}
private IEnumerable<GAStatistics> CreateCompaniesList()
{
List<GAStatistics> ListGaVisitors = new List<GAStatistics>();
foreach (var row in d.Rows)
{
GAStatistics GaVisits = new GAStatistics(row[0], row[1]);
ListGaVisitors.Add(GaVisits);
}
return ListGaVisitors;
}
}
我从控制器传递列表到这个视图:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.load("visualization", "1", { packages: ["treemap"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get('/GAStatistics/GetData', {},
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', 'Date');
tdata.addColumn('string', 'Visitors');
for (var i = 0; i < data.length; i++) {
//tdata.addRow([data[i].Year, data[i].Salary, data[i].Expense]);
tdata.addRow([data[i].Date, data[i].Visitors]);
}
var options = {
title: "Expenses, salary For the current year"
};
var chart1 = new google.visualization.AreaChart(document.getElementById('chart_div1'));
chart1.draw(tdata, options);
});
}
</script>
有什么想法吗?
【问题讨论】:
-
您应该将您的 C# datetime 字符串转换为 javascript Date 类型。它应该类似于
tdata.addRow([new Date(2014,1,1)...,但您应该使用自己的解析函数而不是new Date。也许通过将 C# 日期时间转换为时间戳数字,如下所述:stackoverflow.com/a/7596509/427225 -
data长什么样子? -
感谢 vorrtex。那么在javascript中将字符串值转换为日期值是必要的吗?实际上,我在编写此代码时遵循了一个指南,那个人在列表中使用 Year 属性编写了类似的内容 - Year = new DateTime(2014, 3, 1).ToString("yyyy/mm/dd") asgaliant - 我不知道不知道,这就是我的全部,在网上找到了一个例子。
-
不知道你的
string Date是怎么转换的。但是,如果您的日期字符串看起来像“2011-10-20”、“1999/01/31”或“1990 年 1 月 1 日”,那么它很容易被 javascript 解析,例如new Date("2011-10-20")。在某处放置一个调试断点并查看Date属性的值。 -
哦,好吧。好吧,“日期”是来自 C# 类 GAStatistics 的字符串属性,该类还包含一个名为“访客”的字符串属性。日期格式为“2014-01-24”,访客只包含“873”之类的数字。
标签: c# javascript asp.net-mvc charts google-visualization