Asp.net mvc 使用echart的一点点经验

最近做项目需要用到图表,发现echart是一个非常强大的工具。而我在使用它的三个月中,使用它的方法也在逐渐深入

最开始使用时,js和后台代码都不是特别了解,于是使用最笨的办法,仿照官网,将option在前台配置好,使用ajax请求数据并填充数据,代码如下

前台代码

 function GetStatic(u1,year1,month1,day1,year2,month2,day2) {
        $.ajax({
            type: "GET",
            url: "GetFlowMoreDate",
            data: { uid: u1, year1: year1, month1: month1, day1: day1, year2: year2, month2: month2, day2: day2 },
            dataType: "json",
            success: function (data) {
                var dataObj = eval("(" + data + ")");
                var Total = new Array();
                var StartTime = new Array();
                var Max = new Array();
                var Min = new Array();
                for (var i = 0; i < dataObj.length; i++) {
                    StartTime[i] = dataObj[i].StartTime;
                    Max[i] = dataObj[i].Data1;
                    Min[i] = dataObj[i].Data2
                }
                echart( Max, Min, StartTime);
            }
        })
    }
    function echart( Max, Min, StartTime) {
        // 路径配置
        require.config({
            paths: {
                echarts: 'http://echarts.baidu.com/build/dist'
            }
        });

        // 使用
        require(
            [
                'echarts', 'echarts/chart/line',
                'echarts/chart/bar' // 使用柱状图就加载bar模块,按需加载
            ],
              function (ec) {
                  // 基于准备好的dom,初始化echarts图表
                  var myChart = ec.init(document.getElementById('main'));
                  var option = {

                      calculable: true,
                      title: {
                          text: ' ',
                          subtext: ' '
                      },
                      tooltip: {
                          trigger: 'axis'
                      },
                      legend: {
                          data: ['1', '2'], y: 25
                      },
                      grid: {
                          x: 45, x2: 20

                      },
                      toolbox: {
                          show: true,

                          feature: {

                              dataZoom: { show: true },
                              dataView: { show: true },
                              restore: { show: true },
                              saveAsImage: { show: true }
                          }
                      },
                      dataZoom: {
                          y2: 370,
                          show: true,
                          realtime: true,
                          start: 0,
                          end: 100
                      },
                      calculable: true,
                      xAxis: [
                          {
                              type: 'category',
                              boundaryGap: true,
                              data: StartTime//x轴的一组数值
                          }
                      ],
                      yAxis: [
                          {
                              type: 'value',
                              axisLabel: {
                                  formatter: '{value} m³'
                              }
                          }
                      ],
                      series:[
                    {
                        name: '1',//最高气温
                        type: 'line',
                        data: Max,//y轴的一组数值

                    },
                      {
                          name: '2',//最高气温
                          type: 'line',
                          data: Min,//y轴的一组数值

                      },
                      ]
                  };
                  myChart.hideLoading();
                  // 为echarts对象加载数据
                  myChart.setOption(option);
              }
        );
    }
后台代码

     public JsonResult GetFlowMoreDate(string uid, int year1, int month1, int day1, int year2, int month2, int day2)
        {
            Guid u = Guid.Parse(CryptoUtils.DesDecrypt(uid));
            JsonResult ret = new JsonResult();
            ret.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            List<FlowStatisticContract> list = LoadService<IFlowStatisticService>().GetFlowMoreDate(u, year1, month1, day1, year2, month2, day2);
            string json = JsonConvert.SerializeObject(list);
            ret.Data = json;
            return ret;
        }

可是,多做了几个页面以后就发现,这样做太麻烦。每一个页面都需要配置一下echart的option,而且更重要的是,没有办法灵活的改变echart的option,比如多一个数据系列,或者改一个标题。使用mvc的viewdata也太麻烦。

于是我稍稍改了一下,将配置文件抽离出来,不过刚开始并没有想很深,只是想写成一个普适的而且易配置的echart组件

前台代码

  function GetStatic(u, year, month, day) {
        $.ajax({
            type: "GET",
            url: "GetFlowStatisticAll",
            data: { uid: u, year: year, month: month, day: day },
            dataType: "json",
            success: function (e) {
                $("#loading").hide();
                $("#table").children('tr').remove();
                var data = JSON.parse(e);
                var option = {
                    title: {
                        text: '载入中',
                        subtext: '纯属虚构'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: []//颜色标条name,要与数据组的name一致
                    },
                    toolbox: {
                        show: true,
                        feature: {
                            mark: { show: true },
                            dataView: { show: true, readOnly: false },
                            magicType: { show: true, type: ['line', 'bar'] },
                            restore: { show: true },
                            saveAsImage: { show: true }
                        }
                    },
                    dataZoom: {
                        show: true,
                        realtime: true,
                        height: 20,
                        start: 0,
                        end: 100
                    },
                    calculable: true,
                    xAxis: [
                        {
                            type: 'category',
                            boundaryGap: true,
                            data: []//x轴的一组数值
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            axisLabel: {
                                formatter: '{value} m³'
                            }
                        }
                    ],
                    series: [


                    ]
                };
                if (!data["nodata"]) {
                    option["title"]["text"] = data["title"];
                    option["title"]["subtext"] = data["subtitle"];

                    for (var i = 0; i < 3; i++) {
                        option["series"].push(
                        {
                            name: '',
                            type: 'line',
                            data: [],//添加y轴的第二组数值
                            markPoint: {
                                symbolSize: 6,
                                data: [
                                    { type: 'max', name: '最大值' },
                                    { type: 'min', name: '最小值' }
                                ],
                            },
                        }
                        );
                        option["xAxis"][0]["data"] = data["x_data"];
                        option["series"][i]["name"] = data["name" + i];
                        option["series"][i]["data"] = data["y_data" + i];
                        option["legend"]["data"].push(data["name" + i]);
                    }


                    for (var i = 0; i < data["x_data"].length; i++) {
                        var times = data["x_data"][i] + "";
                        if (times.length == 4) {
                            times = times.substr(0, 4) + "-";
                        }
                        else if (times.length == 6) {
                            times = times.substr(0, 4) + "-" + times.substr(4, 2);
                        }
                        else if (times.length == 8) {
                            times = times.substr(0, 4) + "-" + times.substr(4, 2) + "-" + times.substr(6, 2);
                        }
                        else if (times.length == 10) {
                            times = times.substr(0, 4) + "-" + times.substr(4, 2) + "-" + times.substr(6, 2) + " " + times.substr(8, 2) + ":00";
                        }


                        var time = "<th class='text-left'>" + times + "</th>";
                        var max = "<th class='text-right'>" + data["y_data0"][i].toFixed(2) + "</th>";
                        var min = "<th class='text-right'>" + data["y_data1"][i].toFixed(2) + "</th>";
                        var total = "<th class='text-right'>" + data["y_data2"][i].toFixed(2) + "</th>";
                        $("#table").prepend("<tr>" + time + max + min + total + "</tr>");
                    }
                    $("#tablepanel").fadeIn();
                    $("#main").fadeIn();
                    echart(option);
                } else {
                    $("#warning").fadeIn();
                }
            }
        })
    }
 function echart(option) {
        // 路径配置
        require.config({
            paths: {
                echarts: 'http://echarts.baidu.com/build/dist'
            }
        });

        // 使用
        require(
            [
                'echarts', 'echarts/chart/line',
                'echarts/chart/bar' // 使用柱状图就加载bar模块,按需加载
            ],
              function (ec) {
                  // 基于准备好的dom,初始化echarts图表
                  var myChart = ec.init(document.getElementById('main'));
                  myChart.setTheme(getTheme());
                  // 为echarts对象加载数据
                  myChart.setOption(option);
              }
        );
    }


后台代码

     public JsonResult GetFlowStatisticAll(string uid, int year, int month, int day)
        {
            Guid u = Guid.Parse(CryptoUtils.DesDecrypt(uid));
            JsonResult ret = new JsonResult();
            ret.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            List<FlowStatisticContract> list = LoadService<IFlowStatisticService>().GetFlowStatisticByUidAndDate(u, year, month, day);

            Dictionary<string, object> mydic = new Dictionary<string, object>();
            if (list.Count != 0)
            {
                mydic.Add("nodata", false);
                mydic.Add("max", "最大值");
                mydic.Add("x_data", list.Select(p => p.StartTime));
                mydic.Add("y_data0", list.Select(p => p.Data1));
                mydic.Add("y_data1", list.Select(p => p.Data2));
                mydic.Add("y_data2", list.Select(p => p.Data3));
                mydic.Add("name0", "最大");
                mydic.Add("name1", "最小");
                mydic.Add("name2", "总量");
                if (year == -1)
                {
                    mydic.Add("title", "年度对比");
                }
                else if (month == -1)
                {
                    mydic.Add("title", year + "年");
                }
                else if (day == -1)
                {
                    mydic.Add("title", year + "年" + month + "月");
                }
                else
                {
                    mydic.Add("title", year + "年" + month + "月" + day + "日");
                }

                mydic.Add("subtitle", "");
            }
            else
            {
                mydic.Add("nodata", true);
            }
            string json = JsonConvert.SerializeObject(mydic);
            ret.Data = json;
            return ret;
        }

这样子写以后,用起来是简单了,可是代码维护性太差。特别是那么一大堆字典类型的东西,我估计自己隔了几个月再想做点修改都不好改

再经过几次测试以后。到目前为止,个人发现的最简单的方式就是这样

后台代码

      public JsonResult GetData(Guid id)
        {
            JsonResult json = new JsonResult();
            string[] s = { "销量" };
            string[] s1 = { "衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子" };
            int[] d = { 5, 20, 40, 10, 10, 20 };

            JObject option = new JObject()
            {
                new JProperty("tooltip", new JObject { new JProperty("show", true) }),
                new JProperty("legend", new JObject { new JProperty("data", s) }),
                new JProperty("xAxis", new JObject[] {new JObject { new JProperty("type", "category"), new JProperty("data", s1) } }),
                new JProperty("yAxis", new JObject[] { new JObject { new JProperty("type", "value") } }),
                new JProperty("series",new JObject []{new JObject { new JProperty("name", "销量"), new JProperty("type", "bar"), new JProperty("data", d) } }),
            };
            json.Data = JsonConvert.SerializeObject(option);

            return json;

        }
前台代码

    function start() {
        $.ajax({
            type: "POST",
            url: "/factory/GetData",
            data: { id: "@Model.F_Uid" },
            dataType: "json",
            success: function (e) {
                require.config({
                    paths: {
                        echarts: 'http://echarts.baidu.com/build/dist'
                    }
                });
                // 使用
                require(
                    [
                        'echarts',
                        'echarts/chart/bar' // 使用柱状图就加载bar模块,按需加载
                    ],
                    function (ec) {
                        // 基于准备好的dom,初始化echarts图表
                        var myChart = ec.init(document.getElementById('main'));
                        // 为echarts对象加载数据
                        myChart.setOption(JSON.parse(e));
                    }
                );
            }
        })
    }

代码的可维护性上升了好多个级别,而且代码量更少了

其实还可以更加简单的

可以直接使用匿名对象 ret.Data= new{Id=xx,Name=xx};

这时 MVC会将其自动序列化为 JSON 在前段也不需要再转化


如果不希望使用JsonResult 的话 其实也可以在cshtml中 首先将其转化为字符串

 string str=JsonConvert.SerializeObject(data)
然后使用@html.Raw(str)
算是新的两种思路吧

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值