我正在尝试使用MVC中的JSon操作方法的结果创建一个非常简单的条形图.我得到了实际的条形图,但我不明白这些选项以及所有这些,所以我基本上猜测该怎么做.我使用HighCharts网站上的示例
这是HighCharts jQuery代码:
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); }); }
这是返回JSon的action方法:
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); }
我能够创建一个饼图,但现在当我想创建一个简单的栏时,我无法弄清楚jQuery代码中的内容,因此我得到的结果是一个首先是唯一用户的栏图例中列出的是数组中的最后一个.其次,工具提示显示x = [用户名],y = 29,而不是[用户名]:29,这是我在饼图中得到的.
如何从这个JSon在HighCharts中创建这样一个简单的条形图?
我用://Controller action: public JsonResult GetData(int id) { Dictionary<int, double> data = this.repository.GetData(id); return Json(data.ToArray(), JsonRequestBehavior.AllowGet); }
视图:
<script> var chart1; $(document).ready(function () { chart1 = new Highcharts.Chart({ chart: { renderTo: 'chart-container-1', defaultSeriesType: 'scatter', events: { load: requestData } }, options... , series: [{ name: 'some data', data: [] }] }); } ); function requestData() { $.ajax({ url: '/ControllerName/GetData?id=@(Model.Id)', success: function (items) { $.each(items, function (itemNo, item) { chart1.series[0].addPoint([item.Key,item.Value], false); }); chart1.redraw(); }, cache: false }); } </script> <div id="chart-container-1"></div>
所以基本上我使用addPoint(‘x,y’数组,false表示不重绘图表)