I'm trying to create a very simple bar chart using the results of a JSon action method in MVC. I get the actual bar chart, but I don't understand the options and all that well enough, so I'm basically guessing what to do. I used the example on the HighCharts site as an example for how to get data from server code and create a chart. The difference is my chart is simpler than the example. I don't have categories for each user (as in the fruit example), I only have a user and a number of hours logged.
Here's the HighCharts jQuery code:
function getHighChart() {
var actionUrl = '<%= Url.Action("GetChartData") %>';
var customerId = $('#customersId').val();
var startdate = $('.date-pickStart').val();
var enddate = $('.date-pickEnd').val();
var options = {
chart: {
renderTo: 'chart-container',
defaultSeriesType: 'bar'
},
title: {
text: 'Statistik'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Timmar'
}
},
series: []
}
jQuery.getJSON(actionUrl,
{ customerId: customerId, startdate: startdate, enddate: enddate }, function (items) {
var series = {
data: []
};
$.each(items, function (itemNo, item) {
series.name = item.Key;
series.data.push(parseFloat(item.Value));
});
options.series.push(series);
var chart = new Highcharts.Chart(options);
});
}
And here's the action method returning JSon:
public JsonResult GetChartData(string customerId, string startdate, string enddate)
{
int intcustomerId = Int32.Parse(customerId);
var emps = from segment in _repository.TimeSegments
where
segment.Date.Date >= DateTime.Parse(startdate) &&
segment.Date.Date <= DateTime.Parse(enddate)
where segment.Customer.Id == intcustomerId
group segment by segment.Employee
into employeeGroup
select new CurrentEmployee
{
Name = employeeGroup.Key.FirstName + " " + employeeGroup.Key.LastName,
CurrentTimeSegments = employeeGroup.ToList(),
CurrentMonthHours = employeeGroup.Sum(ts => ts.Hours)
};
Dictionary<string, double > retVal = new Dictionary<string, double>();
foreach (var currentEmployee in emps)
{
retVal.Add(currentEmployee.Name, currentEmployee.CurrentMonthHours);
}
return Json(retVal.ToArray(), JsonRequestBehavior.AllowGet);
}
I was able to create a pie chart, but now when I want to create a simple bar I'm not able to work out what is what in the jQuery code, so the results I get is a bar where first of all the only user listed in the legend is the last one in the array. Secondly, the tooltip shows x = [The user's name], y = 29, instead of [The user's name]: 29, which I got in the pie chart.
How would I create such a simple bar chart in HighCharts from this JSon?
Well, I worked it out myself after all... I thought I should post it in case some other HighCharts newbie like me is interested:
Here's the jQuery that worked:
If someone can find faults in this and point me to a better way to do it, I'll gladly hand over the answer credit, otherwise I'll accept my own answer...
I use:
View:
So basically I use addPoint('array of x,y',false for not redrawing chart)