Pregunta

Estoy intentando crear un gráfico de barras muy simple usando los resultados de un método de acción JSON en MVC. Me sale el gráfico de barras real, pero no entiendo las opciones y todo lo que lo suficientemente bien, así que estoy básicamente adivinar qué hacer. He utilizado el ejemplo en el sitio Highcharts como un ejemplo de cómo obtener los datos de código de servidor y crear un gráfico. La diferencia es mi carta es más simple que el ejemplo. No tener categorías para cada usuario (como en el ejemplo de la fruta), sólo tengo un usuario y un número de horas registradas.

Aquí hay código de los 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);
                        });                        
        }

Y aquí está el método de la acción de volver 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 fue capaz de crear un gráfico circular, pero ahora cuando quiero crear una barra sencilla que no soy capaz de averiguar qué es lo que en el código de jQuery, por lo que los resultados que se obtiene es un bar en el primer lugar el único usuario que aparece en la leyenda es la última en la matriz. En segundo lugar, los espectáculos tooltip x = [nombre del usuario], y = 29, en lugar de [nombre del usuario]:. 29, que llegué en el gráfico de sectores

¿Cómo puedo crear tal un simple gráfico de barras en Highcharts de esta JSON?

¿Fue útil?

Solución 2

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

Otros consejos

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)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top