6

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
WhoAmI
  • 1,188
  • 6
  • 17
  • 47
  • You should convert your C# datetime string to the javascript Date type. It should be something like `tdata.addRow([new Date(2014,1,1)...`, but instead of `new Date` you should use your own parsing function. Maybe by converting C# datetime to a timestamp number like it is explained here: http://stackoverflow.com/a/7596509/427225 – vortexwolf Mar 14 '14 at 19:52
  • What does `data` look like? – asgallant Mar 14 '14 at 19:52
  • Thanks vorrtex. So it's nessesary to convert the string value to the date value in javascript? I actually followed a guide when writing this code and that guy wrote something like this with a Year property in a list - Year = new DateTime(2014, 3, 1).ToString("yyyy/mm/dd") asgaliant - I don't know, this is all ive got, found an example online. – WhoAmI Mar 14 '14 at 20:21
  • I don't know how your `string Date` can be converted. But if your date string looks like "2011-10-20", or "1999/01/31", or "01 Jan 1990" it will be easily parsed by javascript, for example `new Date("2011-10-20")`. Put a debug breakpoint somewhere and look what value the `Date` property has. – vortexwolf Mar 14 '14 at 23:16
  • Oh okej. Well "Date" is a string property from C#-class GAStatistics, this class also contain a string property called Visitors. Date is formated like "2014-01-24" and Visitors just contains numbers like "873". – WhoAmI Mar 15 '14 at 11:04

1 Answers1

5

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.

vortexwolf
  • 13,967
  • 2
  • 54
  • 72
  • Nice! been trying to figure this out for a week or so. I'm now getting number of visitors in a column chart but Dates are not showing at all but, it says "NaN NaN and a value. However if a change Date to number and use pareInt the values are diaplayed correctly like this:http://imageshack.com/a/img534/2263/m5xn.png Hers what i'm getting using "date" - Line Chart: imageshack.com/i/nmq2typ Column chart : imageshack.com/i/nr4ziop Thanks again! – WhoAmI Mar 15 '14 at 19:20
  • 1
    @KristofferAndersson The tooltip "20140126" seems to be a date "2014-01-26" without hyphens, that's why it doesn't work. This can be fixed by adding these hyphens and using code like `str.substr(0, 4)+"-"+str.substr(4,2)+"-"+str.substr(6,2)`. This way should be better because tooltips and labels will display more logical date values instead of numbers. – vortexwolf Mar 15 '14 at 20:19
  • @KristofferAndersson I updated the code in my answer, you can try it. If it doesn't work, you may post a new question on this website. – vortexwolf Mar 15 '14 at 20:30
  • Hi vorrtex, sorry to dig this up again but i was wondering what the numbers (0,4), (4,2) and (62) means. Would be nice understand this code fully. Thank you – WhoAmI Apr 18 '14 at 08:09
  • @KristofferAndersson I used the built-in javascript function `substr`, you can read about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr For example, parameters (0,4) mean start from the index 0 (str[0]) and take 4 characters, `"abcdef".substr(0,4) //abcd`, parameters (4,2) - start from str[4] and take 2 characters `"abcdef".substr(4,2) // ef`. You can use Chrome Developer Tools (press F12), open the Console tab and test any javascript code. – vortexwolf Apr 18 '14 at 08:54
  • Oh i see, index position followed by nr of characters. This is great. Thx alot! – WhoAmI Apr 18 '14 at 08:57