I'm trying to display some data in Google Charts but get this error:
Data column(s) for axis #0 cannot be of type string..
I have two properties from this class:
public class GAStatistics
{
public string Date { get; set; }
public string Visitors { get; set; }
}
I'm passing this a list of these properties from this controller:
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;
}
}
To this view of which I pass the list from the controller:
<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>
Any idea?
I have tested your example and found out that the main issue is because the second column Visitors
should be a number instead of a string.
I have replaced the column type in the tdata.addColumn('number', 'Visitors');
line and added parseInt
inside the loop:
tdata.addColumn('date', 'Date');
tdata.addColumn('number', 'Visitors');
// sample data: var data = [{ Date: "20140124", Visitors: "873" }, { Date: "20140125", Visitors: "875" }];
for (var i = 0; i < data.length; i++) {
var dateStr = data[i].Date.substr(0, 4) + "-" + data[i].Date.substr(4,2) + "-" + data[i].Date.substr(6,2);
tdata.addRow([new Date(dateStr), parseInt(data[i].Visitors)]);
}
Also the first column Date
could have remained a string
, but I replaced its type to be date
and added new Date
conversion as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With