简易的highcharts公共绘图模块封装--基于.net mvc

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简易的highcharts公共绘图模块封装--基于.net mvc相关的知识,希望对你有一定的参考价值。

运行效果:

 

技术分享

 

之所以选择这个图表插件,是因为它较其他同类插件轻量且中文文档详细完整,Demo丰富,配置使用简单。具体内容请登录中文官网:http://www.hcharts.cn/

 

项目详细:

项目环境:win10+visual studio 2015 +.net framework 4.5

后台技术:.net mvc + c#

前端技术:Matrixadmin(国外的一款基于bootstrap的后台模板框架)+jquery+highcharts

 

  代码实现:

  1. 设定系统目前支持的图表类型:EnumChartType.cs(以后可以扩充此文件以支持更多的图表类型)
        public enum EnumChartsType:short
        {
            /// <summary>
            /// 柱形图
            /// </summary>
            column=1,
    
            /// <summary>
            /// 折线图
            /// </summary>
            line,
    
            /// <summary>
            /// 条形图
            /// </summary>
            bar,
    
            /// <summary>
            /// 曲线图
            /// </summary>
            spline,
    
            /// <summary>
            /// 区域图
            /// </summary>
            area
        }

     

  2. 封装用于序列化反序列化Json数据的工具类:CommonJson.cs(Json数据用于highcharts的数据源)
            /// <summary>
            /// 序列化
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="obj"></param>
            /// <returns></returns>
            public static string Serialize(object obj)
            {
                DataContractJsonSerializer jsonFormater = new DataContractJsonSerializer(obj.GetType());
    
                using (MemoryStream ms = new MemoryStream())
                {
                    jsonFormater.WriteObject(ms, obj);
                    ms.Position = 0;
                    using (StreamReader sr = new StreamReader(ms))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
    
            /// <summary>
            /// 反序列化
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="jsonDatas"></param>
            /// <param name="encoding"></param>
            /// <returns></returns>
            public static T Deserialize<T>(string jsonDatas)
                where T : class
            {
                return Deserialize(jsonDatas, typeof(T)) as T;
            }
    
            public static object Deserialize(string jsonDatas, Type t)
            {
                DataContractJsonSerializer jsonFormater = new DataContractJsonSerializer(t);
                byte[] buffer = Encoding.Unicode.GetBytes(jsonDatas);
                using (MemoryStream ms = new MemoryStream(buffer))
                {
                    ms.Position = 0;
                    object obj = jsonFormater.ReadObject(ms);
                    return obj;
                }
            }

     

  3. 封装highcharts的数据源类ChartData.cs
        /// <summary>
        /// HighCharts数据封装类
        /// </summary>
        public class ChartData
        {
            /// <summary>
            /// 图表类型
            /// </summary>
            public int ChartType { set; get; }
    
            /// <summary>
            /// 图表标题
            /// </summary>
            public string ChartTitle { set; get; }
    
            /// <summary>
            /// x轴分组
            /// </summary>
            public string [] XAxisData{set;get;}
    
            /// <summary>
            /// y轴标题
            /// </summary>
            public string YAxisTitle { set; get; }
    
            /// <summary>
            /// y轴数据(key:列名称,value=列数据)
            /// </summary>
            public Dictionary<string, decimal[]> YAxisData { set; get; }
    
            //处理后
            public string xAxisDataStr { set; get; }
            public string yAxisDataStr { set; get; }
    
        }

     

  4. 创建绘制图表的公共模块,包括:
    Controller:
            /// <summary>
            /// 图表绘制公用
            /// </summary>
            /// <returns></returns>
            public ActionResult Index()
            {
    
                var data = Request.QueryString["data"];
                ChartData chartData = CommonJson.Deserialize<ChartData>(data);
    
                #region 转换x轴分组数据
                //转换x轴分组数据
                chartData.xAxisDataStr = "";
                for (int i = 0; i < chartData.XAxisData.Length; i++)
                {
                    if (i != 0)
                    {
                        chartData.xAxisDataStr += ",";
                    }
    
                    chartData.xAxisDataStr += "" + chartData.XAxisData[i] + "";
                } 
                #endregion
    
                #region 转换y轴分组数据
                //转换y轴分组数据
                chartData.yAxisDataStr = "";
                int tab = 0;
                foreach (var item in chartData.YAxisData.Keys)
                {
                    string yData = "";
                    for (int i = 0; i < chartData.YAxisData[item].Length; i++)
                    {
                        if (i != 0)
                        {
                            yData += ",";
                        }
                        yData += chartData.YAxisData[item][i];
                    }
    
                    if (tab != 0)
                    {
                        chartData.yAxisDataStr += ",";
                    }
    
                    chartData.yAxisDataStr = "{name:‘" + item + "‘,data:[" + yData + "]}";
    
                    tab++;
                } 
                #endregion
                return View(chartData);
            }

    View:(其中,@html.Raw()的作用是将字符串原文输出,因为从后台传到前台的字符串.net默认会进行转码,当字符串中有单引号等特殊字符时数据会失真)
    @model CollegeManager.Common.Models.ChartData
    @using System.Collections.Generic;
    @using CollegeManager.Common.Utils;
    @{
        ViewBag.Title = "柱形图";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <script type="text/javascript">
        $(function () {
            $(#container).highcharts(
                {
                    chart: { type: @Html.Raw(((EnumChartsType)Model.ChartType).ToString()) },
                    title: { text: @Html.Raw(Model.ChartTitle) },
                    xAxis: {
                        categories: [@Html.Raw(Model.xAxisDataStr)]
                    },
                    yAxis: { title: {text:@Model.YAxisTitle}},
                    series: [@Html.Raw(Model.yAxisDataStr)]
                }
                );
    
        });
    </script>
    <div id="container" style="min-width: 600px; height: 350px"></div>

     

  5. 供js或jquery调用的需要绘图功能的模块中的方法,用以给绘图模块封装数据
            public JsonResult ChartJson()
            {
    
                #region 构造数据
                ChartData chartData = new ChartData();
                chartData.ChartType = (int)EnumChartsType.column;
                chartData.ChartTitle = "柱形图测试用例";
    
                //x轴数据
                chartData.XAxisData = ...... //此处略去
    
                chartData.YAxisTitle += "单位:元";    //y轴标题
    
                chartData.YAxisData = ...... //此处略去
    
                //y轴分组名称
                string yName = "";
    
                //y轴分组数据
                decimal[] yData = new decimal[chartData.XAxisData.Length];
    
                chartData.YAxisData.Add(yName, yData);
                #endregion
    
                return Json(CommonJson.Serialize(chartData));
            }

     


     

以上是关于简易的highcharts公共绘图模块封装--基于.net mvc的主要内容,如果未能解决你的问题,请参考以下文章

Highcharts - 甘特图绘图问题

基于ESP8266的简易气象站

highchart绘图变量问题

Flask 结合 Highcharts 实现动态渲染图表

如何将 Highcharter 绘图保存为本地磁盘上的图像?

html5绘图工具选择