jQuery HighCharts 和 MVC 2 应用程序中的简单条形图?

发布于 2024-10-12 04:06:17 字数 3149 浏览 1 评论 0原文

我正在尝试使用 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 的操作方法:

    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 中创建这样一个简单的条形图?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

强者自强 2024-10-19 04:06:17

我使用:

//Controller action:
public JsonResult GetData(int id)
{
Dictionary<int, double> data = this.repository.GetData(id);
return Json(data.ToArray(), JsonRequestBehavior.AllowGet);
}

View:

<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('array of x,y',false 不重绘图表)

I use:

//Controller action:
public JsonResult GetData(int id)
{
Dictionary<int, double> data = this.repository.GetData(id);
return Json(data.ToArray(), JsonRequestBehavior.AllowGet);
}

View:

<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>

So basically I use addPoint('array of x,y',false for not redrawing chart)

水染的天色ゝ 2024-10-19 04:06:17

好吧,毕竟我自己解决了...我想我应该发布它,以防像我这样的其他 HighCharts 新手感兴趣:

这是有效的 jQuery:

    function getHighChart() {
        var actionUrl = '<%= Url.Action("GetChartData") %>';
        var customerId = $('#customersId').val();
        var customerName = $('#customersId option:selected').text();
        var startdate = $('.date-pickStart').val();
        var enddate = $('.date-pickEnd').val();
        //define the options
        var options = {
            chart: {
                renderTo: 'chart-container',
                defaultSeriesType: 'column'
            },
            title: {
                text: 'Hours worked for ' + customerName
            },
            xAxis: {
                categories: [customerName]
            },
            yAxis: {
                title: {
                    text: 'Hours'
                }
            },
            series: []
        };

        //Calls the JSON action method
        jQuery.getJSON(actionUrl,
                    { customerId: customerId, startdate: startdate, enddate: enddate }, function (items) {

                        $.each(items, function (itemNo, item) {
                            var series = {
                                data: []
                            };
                            series.name = item.Key;
                            series.data.push(parseFloat(item.Value));
                            options.series.push(series);

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

如果有人可以找到其中的错误并为我指出更好的方法这样做,我很乐意交出答案,否则我会接受我自己的答案......

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:

    function getHighChart() {
        var actionUrl = '<%= Url.Action("GetChartData") %>';
        var customerId = $('#customersId').val();
        var customerName = $('#customersId option:selected').text();
        var startdate = $('.date-pickStart').val();
        var enddate = $('.date-pickEnd').val();
        //define the options
        var options = {
            chart: {
                renderTo: 'chart-container',
                defaultSeriesType: 'column'
            },
            title: {
                text: 'Hours worked for ' + customerName
            },
            xAxis: {
                categories: [customerName]
            },
            yAxis: {
                title: {
                    text: 'Hours'
                }
            },
            series: []
        };

        //Calls the JSON action method
        jQuery.getJSON(actionUrl,
                    { customerId: customerId, startdate: startdate, enddate: enddate }, function (items) {

                        $.each(items, function (itemNo, item) {
                            var series = {
                                data: []
                            };
                            series.name = item.Key;
                            series.data.push(parseFloat(item.Value));
                            options.series.push(series);

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

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文