Thomas
Thomas

Reputation: 5998

Displaying date on the x axis with Highcharts using ASP.NET MVC

I have the following C# code:

public JsonResult Graph()
{
    var result = new Dictionary<DateTime, decimal> { { DateTime.Today.ToUniversalTime(), 1000 }, { DateTime.Today.AddDays(-1).ToUniversalTime(), 2000 }, { DateTime.Today.AddDays(-2).ToUniversalTime(), 5000 } };

    return Json(result.ToArray(), JsonRequestBehavior.AllowGet);
}

When I look in firebug the JSON data looks like:

[{"Key":"\/Date(1319515200000)\/","Value":1000},{"Key":"\/Date(1319428800000)\/","Value":2000},{"Key":"\/Date(1319342400000)\/","Value":5000}]

My Highcharts configurations looks like:

var options = {
    chart: {
        renderTo: 'chart',
    },
    xAxis: {
        type: 'datetime'
    },
    series: []
}

jQuery.getJSON("/graph", null, function (items) {
    var series = {
        type: 'column',
        data: []
    };

    jQuery.each(items, function (itemNo, item) {
        series.data.push({
            name: item.Key,
            y: item.Value
        })
    });

    options.series.push(series);

    chart = new Highcharts.Chart(options);
    chart.render();
});

The x-axis will not display my dates. Any help is much appreciated.

Upvotes: 1

Views: 2514

Answers (2)

Thomas
Thomas

Reputation: 5998

I ended up using:

Dictionary<string, decimal>()

I basically passed the date as a string to the view and ended up using

Date.parse(item.Key)

on the client side. It works just fine.

Upvotes: 1

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

Assuming, item.Key contains something like "Date(1319342400000)", can you try the following:

jQuery.each(items, function (itemNo, item) {
    var dateStr = item.Key;
    var dateVal = dateStr.substring(dateStr.indexOf('(')+1, dateStr.indexOf(')'));
    series.data.push([dateVal, item.Value]);
});

Also, you do not need the following line:

chart.render();

And if the above does not work, can you check the value of item.Key as follows:

jQuery.each(items, function (itemNo, item) {
    alert(item.Key);
    series.data.push(//...

Update:

Then you do not need to use substring and indexOf. Just change you jQuery.each as follows:

jQuery.each(items, function (itemNo, item) {        
    series.data.push([item.Key, item.Value]);
});

Upvotes: 0

Related Questions