如何显示JQPLOT图表而不是长文本

4

我有一个在控制器类中的方法,它返回 JSON 数据:

public ActionResult ChartDataJSON()
{
    Chart chart = new Chart();
    DataSet ds = dbLayer.GetChartData();
    DataTable dtChartData = ds.Tables[0];
    List<jqplotModel> chartData = new List<jqplotModel>();

    if (dtChartData .Rows.Count != 0)
    {
        foreach (DataRow row in dtChartData .Rows)
        {
            chartData.Add(new jqplotModel{ Date = DateTime.Parse(@row["Date"].ToString()), Demand= Convert.ToDouble(@row["Demand"].ToString()), Supply= Convert.ToDouble(@row["Supply"].ToString()) });
        }
    }
    return Json(chartData, JsonRequestBehavior.AllowGet);
}

有人知道我如何在我的脚本中使用它吗?我尝试过以下几行代码,但图表没有显示出来。

<script type="text/javascript">
    $(document).ready(function () {
        var types = ['Demand', 'Supply'];               

        var rawData =  function (url, plot, options) {
            var ret = null;
            $.ajax({
                // have to use synchronous here, else the function
                // will return before the data is fetched
                async: false,
                url: url,
                dataType: "json",
                success: function (data) {
                    ret = data;
                }
            });
            return ret;
        };

        // The url for our json data
        var jsonurl = "/ChartController/ChartDataJSON";
        var plotData = []

        for (var i = 0; i < rawData.length; i++) {
            //Parse the date.
            var date = new Date(+rawData[i].Date.match(/\d+/));

            plotData[i] = [date, rawData[i].Demand];
        }

        var plotData2 = []

        for (var i = 0; i < rawData.length; i++) {
            //Parse the date.
            var date = new Date(+rawData[i].Date.match(/\d+/));

            plotData2[i] = [date, rawData[i].Supply];
        }

        var plot1 = $.jqplot('chart1', [plotData, plotData2], {
            height: 300,
            width: 300,
            title: 'Demand Supply',
            dataRenderer: rawData,
            dataRendererOptions: {
                unusedOptionalUrl: jsonurl
            },
            series: [
                    {},
                    { yaxis: 'y2axis' }
            ],
            axes: {
                xaxis: {
                    renderer: $.jqplot.DateAxisRenderer,
                    tickOptions: { formatString: '%#I %p' },
                    label: "Date",
                    tickInterval: '4 hour'
                },
                yaxis: {
                    label: "Demand",
                    labelRenderer: $.jqplot.CanvasAxisLabelRenderer

                },
                y2axis: {
                    label: "Supply",
                    labelRenderer: $.jqplot.CanvasAxisLabelRenderer
                }
            },
            highlighter: {
                show: true,
                sizeAdjust: 1
            },
            cursor: {
                show: false
            },
            legend: {
                show: true,
                labels: types,
                location: 'ne'
            }
        });

        $(window).bind('resize', function (event, ui) {
            if (plot1) {
                plot1.replot();
            }
        });
    });
</script>

当我运行这个程序时,我看不到图表,页面显示了一长串文本,类似于这样:
[{"Demand":4422.45,"Supply":17660,"Date":"/Date(1236504600000)/","DateString":"3 PM"},{"Demand":5019.27,"Supply":20699,"Date":"/Date(1236508200000)/","DateString":"4 PM"},{"Demand":5030.35,"Supply":19917,"Date":"/Date(1236511800000)/","DateString":"5 PM"},{"Demand":5172.35,"Supply":23597,"Date":"/Date(1236515400000)/","DateString":"6 PM"},{"Demand":5656.51,"Supply":21572,"Date":"/Date(1236519000000)/","DateString":"7 PM"},{"Demand":4622.88,"Supply":7794,"Date":"/Date(1236522600000)/","DateString":"8 PM"},{"Demand":3116.21,"Supply":3427,"Date":"/Date(1236526200000)/","DateString":"9 PM"},{"Demand":1588.83,"Supply":1883,"Date":"/Date(1236529800000)/","DateString":"10 PM"},{"Demand":1394.15,"Supply":1403,"Date":"/Date(1236533400000)/","DateString":"11 PM"},{"Demand":1321.76,"Supply":3755,"Date":"/Date(1236537000000)/","DateString":"12 AM"},{"Demand":1130.98,"Supply":3474,"Date":"/Date(1236540600000)/","DateString":"1 AM"},{"Demand":1277.1,"Supply":1072,"Date":"/Date(1236544200000)/","DateString":"2 AM"},{"Demand":1214.68,"Supply":1025,"Date":"/Date(1236547800000)/","DateString":"3 AM"},{"Demand":2117.91,"Supply":1198,"Date":"/Date(1236551400000)/","DateString":"4 AM"},{"Demand":1658.97,"Supply":1485,"Date":"/Date(1236555000000)/","DateString":"5 AM"},{"Demand":1997.36,"Supply":3126,"Date":"/Date(1236558600000)/","DateString":"6 AM"},{"Demand":2147.37,"Supply":4785,"Date":"/Date(1236562200000)/","DateString":"7 AM"},{"Demand":2114.13,"Supply":5268,"Date":"/Date(1236565800000)/","DateString":"8 AM"},{"Demand":2389.84,"Supply":5264,"Date":"/Date(1236569400000)/","DateString":"9 AM"},{"Demand":2240.77,"Supply":5526,"Date":"/Date(1236573000000)/","DateString":"10 AM"},{"Demand":1802.43,"Supply":4530,"Date":"/Date(1236576600000)/","DateString":"11 AM"},{"Demand":1929.71,"Supply":6618,"Date":"/Date(1236580200000)/","DateString":"12 PM"},{"Demand":545.65,"Supply":2767,"Date":"/Date(1236583800000)/","DateString":"1 PM"},{"Demand":0,"Supply":1,"Date":"/Date(1236587400000)/","DateString":"2 PM"}]
请问有谁能帮我找出问题,告诉我在哪里以及我做了什么错误?

编辑: 请注意,数据将是动态的,并且它将来自数据库,通过控制器类中的编码,它将返回JSON脚本到视图。请建议如何在jqPlot中传递/使用JSON对象(从ChartDataJSON()方法)。


我不知道答案,但你有没有看过针对MVC的DotNet Highcharts? http://dotnethighcharts.codeplex.com/ - WannaCSharp
3个回答

3
好的,这是我的答案。
我的控制器如下:
public class jqPlotController : Controller
{    
    public ActionResult ChartDataJSON()
    {
        var chartData = new List<jqplotModel>();

        var point1 = new jqplotModel { Date = DateTime.Now.Date.ToString("yyyy-MM-dd h:mmtt"), Demand = Convert.ToDouble(1), Supply = Convert.ToDouble(3) };
        var point2 = new jqplotModel { Date = DateTime.Now.AddDays(10).Date.ToString("yyyy-MM-dd h:mmtt"), Demand = Convert.ToDouble(2), Supply = Convert.ToDouble(4) };
        var point3 = new jqplotModel { Date = DateTime.Now.AddDays(31).Date.ToString("yyyy-MM-dd h:mmtt"), Demand = Convert.ToDouble(6), Supply = Convert.ToDouble(6) };
        var point4 = new jqplotModel { Date = DateTime.Now.AddDays(106).Date.ToString("yyyy-MM-dd h:mmtt"), Demand = Convert.ToDouble(4), Supply = Convert.ToDouble(2) };
        chartData.Add(point1);
        chartData.Add(point2);
        chartData.Add(point3);
        chartData.Add(point4);

        return Json(chartData, JsonRequestBehavior.AllowGet);
    }

    //
    // GET: /jqPlot/

    public ActionResult Index()
    {
        return View();
    }
}

而且模型:

public class jqplotModel
{
 public string Date { get; set; }
 public double Demand { get; set; }
 public double Supply { get; set; }
}

我已经在ChartDataJSON方法中硬编码了一个(非常简单的!)数据集。您很容易将代码重构为以类似格式输出数据。
由于我是jqPlot的新手,所以花了一些时间才弄清楚如何将DateTime对象传递给这个JavaScript库。每次我尝试时,jqPlot都会给我提供相当神秘的与时间相关的错误消息。我找到的解决方案是将其格式化为jqPlot可以理解的日期时间格式,例如“2008-09-30 4:00PM”(请参见示例here)-我相信这对于其他困惑于jqPlot处理日期的人也会有用!
视图如下:
<script src="@Url.Content("Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("Scripts/jqPlot/jquery.jqplot.js")"  type="text/javascript"></script>
<script src="@Url.Content("Scripts/jqPlot/plugins/jqplot.barRenderer.min.js")"  type="text/javascript"></script>
<script src="@Url.Content("Scripts/jqPlot/plugins/jqplot.categoryAxisRenderer.min.js")"  type="text/javascript"></script>
<script src="@Url.Content("Scripts/jqPlot/plugins/jqplot.dateAxisRenderer.min.js")"  type="text/javascript"></script>
<script src="@Url.Content("Scripts/jqPlot/plugins/jqplot.pointLabels.min.js")"  type="text/javascript"></script>
<script src="@Url.Content("Scripts/jqPlot/plugins/jqplot.canvasAxisTickRenderer.min.js")"  type="text/javascript"></script>
<script src="@Url.Content("Scripts/jqPlot/plugins/jqplot.highlighter.min.js")"  type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function () {
        // The url for our json data
        var url = '@Url.Action("ChartDataJSON", "jqPlot")';

        var ret = null;
        $.ajax({
            // have to use synchronous here, else the function 
            // will return before the data is fetched
            async: false,
            url: url,
            dataType: "json",
            success: function (data) {
                ret = data;
            }
        });

        var demands = [];
        var supplys = [];

        for (i = 0; i < ret.length; i++) {
            // Save the data to the relevant array. Note how date at the zeroth position (i.e. x-axis) is common for both demand and supply arrays.
            demands.push([ret[i].Date, ret[i].Demand]);
            supplys.push([ret[i].Date, ret[i].Supply]);
        }

        var plot1 = $.jqplot('chart1', [demands, supplys], {
            title: "Demand Supply",
            axes: {
                xaxis: {
                    renderer: $.jqplot.DateAxisRenderer,
                    tickOptions: {
                        formatString: '%d/%m/%Y'
                    },

                    label: 'Date'
                },
                yaxis: {
                    label: 'Demand'
                },
                y2axis: {
                    label: 'Supply'
                }
            },
            series: [
                { yaxis: 'yaxis', label: 'demands' },
                { yaxis: 'y2axis', label: 'supplys' }
            ],
            highlighter: {
                show: true,
                sizeAdjust: 1
            },
            cursor: {
                show: false
            }
        });
    });
</script>

@{
    ViewBag.Title = "jQPlot Demo";
}

<h2>@ViewBag.Title</h2>
<div id="chart1" style="height: 400px; width: 600px;"></div>

请注意,在我的解决方案中,我没有使用datarender选项。相反,我使用jquery ajax调用检索数据,然后创建两个单独的数组,用于需求和供应数据。这些数组中的每一个都在x轴上具有日期,然后在y轴上具有它们各自的值(因此日期显然是两个数组共同的)。一旦我拥有了这些数据,我就通过jqPlot绘制了它,结果如下图所示:

Graph produced when code is run

还需要进一步完善坐标轴上的刻度和标签,但希望这是你想要的图表类型。如果不是,那么对我来说肯定是一个很好的学习任务,我希望其他人也会觉得这很有用。


你好Fresh,我在我的应用程序中运行了你的代码,但仍然在网页上以这种形式显示文本[{"Date":"2013-10-21 12:00AM","Demand":1,"Supply":3},{"Date":"2013-10-31 12:00AM","Demand":2,"Supply":4},{"Date":"2013-11-21 12:00AM","Demand":6,"Supply":6},{"Date":"2014-02-04 12:00AM","Demand":4,"Supply":2}]我复制了你的代码,没有做任何更改,但仍然看不到图表。你有什么想法为什么它没有显示图表。感谢你的尝试,非常感激! - user1254053
在浏览器调试控制台中检查错误。仔细检查必要的jquery和jqPlot库(即js文件)是否被正确引用。 - Ben Smith
你有检查浏览器调试控制台吗?有错误吗?你在GetChartJson控制器中设置了断点吗?同时,请检查你的Url.Action,即'@Url.Action("ChartDataJSON", "jqPlot")'是否正确匹配你的控制器。 - Ben Smith
没有错误,但图表仍未显示。我在脚本函数中编写了一个警告行,但警告也没有显示出来。无法找出如何解决这个问题,感到非常困扰。 - user1254053
我希望能够附上一个示例应用程序。我在三个不同的浏览器中尝试了这个,结果都是一样的。在调试时,我可以在控制器类中看到JSON数据,并且为了调试,我在JS脚本中编写了这行代码alert(ret);来检查数据,但是当我运行它时,我既看不到警报,也看不到图表。 - user1254053
显示剩余6条评论

1
我认为这应该解决你的问题:JsFiddle链接
我已将rawData声明为一个变量,它将包含ajaxreply json对象。然后我在下面使用该变量来绘制图形。
在您的代码中,我观察到您已经向图表提供了数据,并且还在其中设置了dataRenderer。这是不正确的。DataRenderer examples $(document).ready(function () {
var rawData = [{"Demand":4422.45,"Supply":17660,"Date":"/Date(1236504600000)/","DateString":"3 PM"},{"Demand":5019.27,"Supply":20699,"Date":"/Date(1236508200000)/","DateString":"4 PM"},{"Demand":5030.35,"Supply":19917,"Date":"/Date(1236511800000)/","DateString":"5 PM"},{"Demand":5172.35,"Supply":23597,"Date":"/Date(1236515400000)/","DateString":"6 PM"},{"Demand":5656.51,"Supply":21572,"Date":"/Date(1236519000000)/","DateString":"7 PM"},{"Demand":4622.88,"Supply":7794,"Date":"/Date(1236522600000)/","DateString":"8 PM"},{"Demand":3116.21,"Supply":3427,"Date":"/Date(1236526200000)/","DateString":"9 PM"},{"Demand":1588.83,"Supply":1883,"Date":"/Date(1236529800000)/","DateString":"10 PM"},{"Demand":1394.15,"Supply":1403,"Date":"/Date(1236533400000)/","DateString":"11 PM"},{"Demand":1321.76,"Supply":3755,"Date":"/Date(1236537000000)/","DateString":"12 AM"},{"Demand":1130.98,"Supply":3474,"Date":"/Date(1236540600000)/","DateString":"1 AM"},{"Demand":1277.1,"Supply":1072,"Date":"/Date(1236544200000)/","DateString":"2 AM"},{"Demand":1214.68,"Supply":1025,"Date":"/Date(1236547800000)/","DateString":"3 AM"},{"Demand":2117.91,"Supply":1198,"Date":"/Date(1236551400000)/","DateString":"4 AM"},{"Demand":1658.97,"Supply":1485,"Date":"/Date(1236555000000)/","DateString":"5 AM"},{"Demand":1997.36,"Supply":3126,"Date":"/Date(1236558600000)/","DateString":"6 AM"},{"Demand":2147.37,"Supply":4785,"Date":"/Date(1236562200000)/","DateString":"7 AM"},{"Demand":2114.13,"Supply":5268,"Date":"/Date(1236565800000)/","DateString":"8 AM"},{"Demand":2389.84,"Supply":5264,"Date":"/Date(1236569400000)/","DateString":"9 AM"},{"Demand":2240.77,"Supply":5526,"Date":"/Date(1236573000000)/","DateString":"10 AM"},{"Demand":1802.43,"Supply":4530,"Date":"/Date(1236576600000)/","DateString":"11 AM"},{"Demand":1929.71,"Supply":6618,"Date":"/Date(1236580200000)/","DateString":"12 PM"},{"Demand":545.65,"Supply":2767,"Date":"/Date(1236583800000)/","DateString":"1 PM"},{"Demand":0,"Supply":1,"Date":"/Date(1236587400000)/","DateString":"2 PM"}];
var types = ['Demand', 'Supply'];
var plotData = []
for (var i = 0; i < rawData.length; i++) { //解析日期。 var date = new Date(+rawData[i].Date.match(/\d+/));
plotData[i] = [date, rawData[i].Demand]; }
var plotData2 = []
for (var i = 0; i < rawData.length; i++) { //解析日期。 var date = new Date(+rawData[i].Date.match(/\d+/));
plotData2[i] = [date, rawData[i].Supply]; }
var plot1 = $.jqplot('chart1', [plotData, plotData2], { height: 300, width: 300, title: '需求供应', //dataRenderer: rawData, //dataRendererOptions: { // unusedOptionalUrl: jsonurl //}, series: [ {}, { yaxis: 'y2axis' } ], axes: { xaxis:

谢谢你,Gyandeep,但这不是我想要的。我的数据将会是动态的,并且将来自数据库。如果我硬编码数据作为变量,我已经知道它可以工作了。任何使用jqplot的人都知道这一点。我想知道如何从控制器类传递json字符串到视图中。希望你了解MVC概念。 - user1254053

0

@user1254053 一样,我也遇到了在实施@Fresh的解决方案时的困难。

我尝试将js代码写在我的ChartDataJSON视图中,也就是在ChartDataJSON()方法的视图中编写代码,但在运行视图时只得到了纯文本对象。

然后我尝试将我的视图代码写在另一个视图中,例如index视图或任何其他仅具有return(View)语句的视图,并成功了。

我希望这可以帮助其他人,也希望我没有太迟。


你在实现方面遇到了什么问题?也许我可以帮忙。 - Ben Smith
我想我已经在我的回答中解释过了。我尝试了一种方法失败了,然后尝试了另一种方法成功了。我认为这就是@user1254053遇到困难的原因,这就是我发布这个答案的原因。 - Watchmaker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接