从highcharts.js中的控制器获取json数据

时间:2012-06-01 18:39:07

标签: javascript asp.net-mvc-3 highcharts

我正在尝试制作一个高清图,它应该显示每种类型的预留房间数量:

这是我的控制器,使用GetHighChart方法:

 public JsonResult GetHighChart()
    {
        var viewModel = Reservation.RoomTypeByDate(5);
        var result = new JsonResult { Data = viewModel};
        return result;

    }

Reservetion.RoomTypeByDate如下所示:

 public static List<dynamic> RoomTypeByDate(int? LunaDorita)
    { 
    var result=DBContext.Current.ExecuteProcedure("RoomtypeCountbydate",
      new QueryParam<int>("@p_ID", LunaDorita.Value)).Map();
    return result;

这是我的存储过程:

SELECT Room_Type, COUNT(*) AS NumarRezervari
FROM   dbo.Reservation re
JOIN   dbo.Room ro ON ro.RoomID = re.Room_ID
JOIN   dbo.Room_Type rt ON rt.RoomType_ID = ro.Room_Type_ID
WHERE  MONTH(re.Data_Check_in)=@p_ID
GROUP  BY Room_Type

我的Json结果是:

[[{"Key":"Room_Type","Value":"Double"},{"Key":"NumarRezervari","Value":2}],      [{"Key":"Room_Type","Value":"LUXURY"},{"Key":"NumarRezervari","Value":1}],[{"Key":"Room_Type","Value":"Triple"},{"Key":"NumarRezervari","Value":1}]]

我应该如何修改这个javascript文件,以便代替下面的系列从myReports controler获取我的GetHighChart方法中的数据。所以我想让我的RoomType为Double而不是数据让我的自己的数据[2,5 ....]?

$(function () {
    var chart;
    $(document).ready(function () {
        chart = new Highcharts.Chart({

            chart: {
                renderTo: 'container',
                type: 'line'

           },
            title: {
                text: 'Monthly Average Temperature'
            },
            subtitle: {
                text: 'Source: WorldClimate.com'
            },
            xAxis: {
                categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
            },
            yAxis: {
                title: {
                    text: 'Temperature (°C)'
                }
            },
            tooltip: {
                enabled: false,
                formatter: function () {
                    return '<b>' + this.series.name + '</b><br/>' +
                        this.x + ': ' + this.y + '°C';
                }
            },
            plotOptions: {
                line: {
                    dataLabels: {
                        enabled: true
                    },
                    enableMouseTracking: false
                }
            },
            series: [{
                name: 'Tokyo',
                data: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
            }, {
                name: 'London',
                data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
            }]
        });
    });
});

2 个答案:

答案 0 :(得分:2)

如果您使用的是Visual Studio,则可以使用DotNet.Highcharts来更轻松地构建高清图层对象。通过这样做,您可以直接使用Series和Data对象,然后将它们传递给Highcharts。它需要创建JavaScript。下面是我如何在MVC 3中创建图表的示例。如您所见,我正在使用LINQ to SQL来收集图表所需的数据。我正在创建一个系列列表来保存数据。这是动态完成的,因此我可以根据需要为图表添加尽可能多的系列,而无需事先知道将有多少。然后我创建图表并将系列列表传递给它。

public ActionResult CombinerBarToday(DateTime? utcStartingDate = null,
                                     DateTime? utcEndingDate = null)
{
    //GET THE GENERATED POWER READINGS FOR THE SPECIFIED DATETIME
    var firstQ = from s in db.PowerCombinerHistorys
                 join u in db.PowerCombiners on s.combiner_id equals u.id
                 where s.recordTime >= utcStartingDate
                 where s.recordTime <= utcEndingDate
                 select new
                 {
                     CombinerID = u.name,
                     Current = s.current,
                     RecordTime = s.recordTime,
                     Voltage = s.voltage,
                     Watts = (s.current * s.voltage)
                 };

    //GET A LIST OF THE COMBINERS CONTAINED IN THE QUERY
    var secondQ = (from s in firstQ
                   select new
                   {
                        Combiner = s.CombinerID
                   }).Distinct();

    /* THIS LIST OF SERIES WILL BE USED TO DYNAMICALLY ADD AS MANY SERIES 
     * TO THE HIGHCHARTS AS NEEDED WITHOUT HAVING TO CREATE EACH SERIES INDIVIUALY */
    List<Series> allSeries = new List<Series>();

    TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

    //LOOP THROUGH EACH COMBINER AND CREATE SERIES
    foreach (var distinctCombiner in secondQ)
    {
        var combinerDetail = from s in db2.PowerCombinerHistorys
                 join u in db2.PowerCombiners on s.combiner_id equals u.id
                 where u.name == distinctCombiner.Combiner
                 where s.recordTime >= utcStartingDate
                 where s.recordTime <= utcEndingDate
                 select new
                 {
                     CombinerID = u.name,
                     Current = s.current,
                     RecordTime = s.recordTime,
                     Voltage = s.voltage,
                     Watts = (s.current * s.voltage) / 1000d
                 };


        var results = new List<object[]>();

        foreach (var detailCombiner in combinerDetail)
        {
            results.Add(new object[] { 
                            TimeZoneInfo.ConvertTimeFromUtc(detailCombiner.RecordTime, easternZone), 
                            detailCombiner.Watts });
        }

        allSeries.Add(new Series
        {
            Name = distinctCombiner.Combiner,
            //Data = new Data(myData)
            Data = new Data(results.ToArray())

        });
    }

    Highcharts chart = new Highcharts("chart")
    .InitChart(new Chart { DefaultSeriesType = ChartTypes.Spline, ZoomType = ZoomTypes.X})
    .SetTitle(new Title { Text = "Combiner History" })
    .SetSubtitle(new Subtitle { Text = "Click and drag in the plot area to zoom in" })
    .SetOptions(new GlobalOptions { Global = new Global { UseUTC = false } })
    .SetPlotOptions(new PlotOptions
    {
        Spline = new PlotOptionsSpline
        {
            LineWidth = 2,
            States = new PlotOptionsSplineStates { Hover = new PlotOptionsSplineStatesHover { LineWidth = 3 } },
            Marker = new PlotOptionsSplineMarker
            {
                Enabled = false,
                States = new PlotOptionsSplineMarkerStates
                {
                    Hover = new PlotOptionsSplineMarkerStatesHover
                    {
                        Enabled = true,
                        Radius = 5,
                        LineWidth = 1
                    }
                }
            }
        }
    })
    .SetXAxis(new XAxis
    {
        Type = AxisTypes.Datetime,
        Labels = new XAxisLabels
        {
            Rotation = -45,
            Align = HorizontalAligns.Right,
            Style = "font: 'normal 10px Verdana, sans-serif'"
        },
        Title = new XAxisTitle { Text = "Time(Hour)" },
    })
    .SetYAxis(new YAxis
    {
        Title = new YAxisTitle { Text = "Kilowatt" }
    })

    .SetSeries(allSeries.Select(s => new Series {Name = s.Name, Data = s.Data }).ToArray());

    return PartialView(chart);
}

答案 1 :(得分:2)

请按照以下步骤操作: 使图表成为全局变量

var chart;

您可以像这样

为图表定义加载事件
chart = new Highcharts.Chart({    
chart: {
                renderTo: 'container',
                type: 'spline',
                marginRight: 10,
                events: {
                    load: requestData
                    }
                }
            }

这里requestData是一个javascript函数。在此功能中,您可以动态地将数据绑定到图表。

function requestData() {

        var pointArray = [];
        for (var i = 0; i < data2.length; i++) {
            //                    var series, shift;

            //                    var point = new Array(new Date(data2[i].UTC).getTime(), parseFloat(data2[i].Value));
            var point = {
                x: new Date(data2[i].UTC).getTime(),
                y: parseFloat(data2[i].Value)
            };
            chartRTM.series[0].addPoint(point);

        }                
        chartRTM.series[0].redraw();}

注意:这里data2是要绑定的数据的json列表。