4

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

这是我使用 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 控制器的 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]
            }]
        });
    });
});
4

2 回答 2

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 列表。

于 2012-06-09T12:20:04.353 回答
2

如果您使用的是 Visual Studio,则可以使用DotNet.Highcharts来更轻松地构建 highchart 对象。通过这样做,您可以直接使用 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);
}
于 2012-06-03T18:43:10.510 回答