Monday, June 3, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  145] [ 7]  / answers: 1 / hits: 26065  / 10 Years ago, fri, march 14, 2014, 12:00:00

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?


More From » c#

 Answers
2

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.


[#71986] Thursday, March 13, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
everardo

Total Points: 406
Total Questions: 104
Total Answers: 92

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
;