Asp.NET Core制作图表

                                               Asp.NET Core制作图表(折线图,条形图和饼图)

第一步:在原有项目的解决方案右键-->添加-->新建项目,在弹出框选中“类库(.net core)”,类名设为“HighchartsNETCore”

                                                                               图1

 

 

 展开HighchartsNETCore,在其下的“依赖项”右键选中“管理NuGet程序包” ,在弹出框输入“Razor.Runtime”    ,并安装图3蓝色选中部分。                                                                             

                                                                                                           图2

                                                                                                             

                                                                                                        图3

 

 第二步:在HighchartsNETCore右键添加类,类名为HighChartsTagHelper,接下来在它里面写代码:

using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HighchartsNETCore
{
    public class HighChartsTagHelper : TagHelper
    {
        /// <summary>
        /// 图表标题
        /// </summary>
        [HtmlAttributeName("title")]
        public string Title { get; set; }
        /// <summary>
        /// 图表类型
        /// </summary>
        [HtmlAttributeName("type")]
        public ChartType Type { get; set; }
        /// <summary>
        /// 图表2级标题
        /// </summary>
        [HtmlAttributeName("subtitle")]
        public string SubTitle { get; set; }

        /// <summary>
        /// 数据对象
        /// </summary>
        [HtmlAttributeName("series")]
        public ChartsSeries Series { get; set; }

        /// <summary>
        /// 一些附加选项
        /// </summary>
        [HtmlAttributeName("plotoptions")]
        public string PlotOptions { get; set; }
        /// <summary>
        /// X轴选项
        /// </summary>
        [HtmlAttributeName("xAxis")]
        public List<object> XAxis { get; set; }
        /// <summary>
        /// Y轴选项 默认可以只填名称
        /// </summary>
        [HtmlAttributeName("yAxis")]
        public string YAxis { get; set; }

        /// <summary>
        /// 提示格式
        /// </summary>
        [HtmlAttributeName("Tooltip")]
        public string Tooltip { get; set; }
        /// <summary>
        /// 图表层id(容器)
        /// </summary>
        [HtmlAttributeName("id")]
        public string Id { get; set; }

        /// <summary>
        /// 图标下方标识是否显示 默认不显示
        /// </summary>
        [HtmlAttributeName("legend")]
        public bool Legend { get; set; }

        /// <summary>
        /// 高级功能,多个数据集,多条图表,饼图不需要。
        /// </summary>
        [HtmlAttributeName("serieslist")]
        public List<ChartsSeries> SeriesList { get; set; }

        [HtmlAttributeName("width")]
        public int Width { get; set; }

        [HtmlAttributeName("height")]
        public int Height { get; set; }

        private void HighChartsJs(StringBuilder jscode)
        {
            jscode.Append("$(function(){$('#" + Id + "').highcharts({ ");
            jscode.Append("credits: { enabled: false },");
            jscode.Append("chart:{ type: '" + Type.ToString().ToLower() + "'");
            if (Width > 0)
                jscode.Append(",width:" + Width);
            if (Height > 0)
                jscode.Append(",height:" + Height);
            jscode.Append("},");
            if (!string.IsNullOrEmpty(Title))
                jscode.Append("title: { text: '" + Title + "'},");
            if (!string.IsNullOrEmpty(SubTitle))
                jscode.Append("subtitle: { text: '" + SubTitle + "'},");
            //判断类型及数据显示
            if (XAxis != null && Type != ChartType.Pie)
            {
                XAxisToString(jscode, XAxis);
            }
            else if (Series.SeriesData != null && Type != ChartType.Pie)
            {
                XAxisToString(jscode, Series.SeriesData.Keys.ToList());
            }
            else if (SeriesList != null && SeriesList.Count > 0)
            {
                XAxisToString(jscode, SeriesList[0].SeriesData.Keys.ToList());
            }
            if (!string.IsNullOrEmpty(YAxis))
            {
                if (YAxis.IndexOf("title") < 0)
                {
                    jscode.Append("yAxis: { title:{ text:'" + YAxis + "'}},");
                    if (string.IsNullOrEmpty(Tooltip))
                        jscode.Append("tooltip: { valueSuffix:'" + YAxis + "' },");
                }
                else
                {
                    jscode.Append("yAxis: {" + YAxis + "},");
                }
            }
            jscode.Append("legend: { enabled: " + Legend.ToString().ToLower() + " },");
            if (!string.IsNullOrEmpty(Tooltip))
                jscode.Append("tooltip: {" + Tooltip + "},");
            if (!string.IsNullOrEmpty(PlotOptions))
                jscode.Append("plotOptions:{" + PlotOptions + "},");
            //数据处理方法
            SeriesToString(jscode);
            jscode.Append(" }); });");
        }

        private void SeriesToString(StringBuilder sb)
        {
            sb.Append("series: [");
            string seriesdata = string.Empty;
            if (Series.SeriesData != null)
            {
                seriesdata = SeriesDataToString(Series);
            }
            if (SeriesList != null && SeriesList.Count != 0)
            {
                foreach (ChartsSeries ser in SeriesList)
                {
                    seriesdata += SeriesDataToString(ser) + ",";
                }
                seriesdata = seriesdata.TrimEnd(',');
            }
            sb.Append(seriesdata);
            sb.Append("]");
        }

        /// <summary>
        /// 数据部分转成js代码
        /// </summary>
        /// <param name="series"></param>
        /// <returns></returns>
        private string SeriesDataToString(ChartsSeries series)
        {
            string seriesdata = "{ name: '" + series.SeriesName + "',data:[";
            foreach (var item in series.SeriesData)
            {
                seriesdata += "['" + item.Key + "'," + item.Value + "],";
            }
            seriesdata = seriesdata.TrimEnd(',');
            seriesdata += "] }";
            return seriesdata;
        }
        /// <summary>
        /// x轴上数据转换
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="xAxis"></param>
        private void XAxisToString(StringBuilder sb, List<object> xAxis)
        {
            sb.Append("xAxis: { categories: [");
            string xaxis = string.Empty;
            foreach (var item in xAxis)
            {
                xaxis += "'" + item + "',";
            }
            xaxis = xaxis.TrimEnd(',');
            sb.Append(xaxis);
            sb.Append("]},");
        }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (Series == null) return;
            output.Attributes.SetAttribute("title", "HighchartsNET自动生成 By:LineZero");
            output.Attributes.SetAttribute("id", Id);
            StringBuilder style = new StringBuilder("margin:0px auto;min-width:400px;");
            if (Width > 0)
                style.Append($"width:{Width}px;");
            if (Height > 0)
                style.Append($"heigth:{Height}px;");
            output.Attributes.SetAttribute("style", style.ToString());
            output.TagName = "div";
            StringBuilder innerhtml = new StringBuilder();
            innerhtml.Append("<script>");
            HighChartsJs(innerhtml);
            innerhtml.Append("</script>");
            output.PostElement.AppendHtml(innerhtml.ToString());
        }

        public class ChartsSeries
        {
            public object SeriesName { get; set; }
            public Dictionary<object, object> SeriesData { get; set; }
        }
        public enum ChartType
        {
            Column,
            Pie,
            Line,
            Bar
        }
    }
}
View Code

 

新建一个名为HomeController的控制器,直接上代码:

补充说明:(先在Models添加一个Tasks(与数据库同名)模型,Tasks里面包含字段Teachername

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Mvc;

using System.Data;

using System.Text;

using lwz.Models;

using Microsoft.EntityFrameworkCore;

using MySql.Data.MySqlClient;

using lwz.Date;

using Microsoft.AspNetCore.Mvc.RazorPages;

using Microsoft.AspNetCore.Http;

using System.Net.Http.Headers;

using System.IO;

using static HighchartsNETCore.HighChartsTagHelper;

 

namespace lwz.Controllers

{

    public class HomeController : Controller

    {

 

        private DataContext con;

 

        public HomeController(DataContext context)

        {

            this.con = context;

        }//通过析构函数来依赖注入

 

        public IActionResult Index()

        {

            //ChartsSeries series = new ChartsSeries();

            //Dictionary<object, object> dic = new Dictionary<object, object>();

            //Random r = new Random();

            //for (int i = 0; i < 12; i++)

            //{

            //    dic.Add(DateTime.Now.AddDays(i).ToString("yyyyMMdd"), r.Next(20));

            //}

            //series.SeriesName = "温度";

            //series.SeriesData = dic;

            //ViewBag.Series = series;

            return View();

           

        }

 

        public IActionResult ChartHomeworkCount()//单独增加数据

        {

            ChartsSeries series = new ChartsSeries();

            Dictionary<object, object> dic = new Dictionary<object, object>();

 

            var Tasks = from p in con.Tasks

                        select p;

           

            var Tasks1 = Tasks.Where(d => d.Teachername == "宋光");

            dic.Add("宋光", Tasks1.Count());

            Tasks = from p in con.Tasks

                    select p;          

 

            var Tasks2 = Tasks.Where(d => d.Teachername == "习一平");

            dic.Add("习一平", Tasks2.Count());

            Tasks = from p in con.Tasks

                    select p;

 

            var Tasks3 = Tasks.Where(d => d.Teachername == "梁老师");

            dic.Add("梁老师", Tasks3.Count());

            Tasks = from p in con.Tasks

                    select p;

 

            var Tasks4 = Tasks.Where(d => d.Teachername == "马玉");

            dic.Add("马玉", Tasks4.Count());

            Tasks = from p in con.Tasks

                    select p;

 

            var Tasks5 = Tasks.Where(d => d.Teachername == "郭老师");

            dic.Add("郭老师", Tasks5.Count());

            Tasks = from p in con.Tasks

                    select p;

 

            var Tasks6 = Tasks.Where(d => d.Teachername == "李家宝");

            dic.Add("李家宝", Tasks6.Count());

            Tasks = from p in con.Tasks

                    select p;

 

 

            series.SeriesName = "作业量/条";

            series.SeriesData = dic;

            ViewBag.Series = series;

            return View();

        }

 

        public IActionResult Index3()//循环读取多条数据

        {

            //ChartsSeries series = new ChartsSeries();

            //Dictionary<object, object> dic = new Dictionary<object, object>();

            //var kucuns = from p in con.kucun

            //             select p;

            //for (int i = 1; i <= kucuns.Count(); i++) 

            //{

            //    var kucunnum = kucuns.Where(d => d.KucunId == i).FirstOrDefault();

            //    dic.Add(kucunnum.Name, kucunnum.Number);

            //}

            //series.SeriesName = "商品库存量";

            //series.SeriesData = dic;

            //ViewBag.Series = series;

            return View();

        }

    } 

}
HomeController

 

在_ViewImports.cshtml里引入(其中lwz为我原有的项目名,你们因名而异) 

1 @using lwz
2 @using lwz.Models
3 @using lwz.Date
4 @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
5 @addTagHelper *,HighchartsNETCore
_ViewImports.cshtml

 

 在名为Home的文件夹下添加视图ChartHomeworkCount.cshtml视图,直接上代码:

补充:(记得要先引用js代码)

@{
    ViewData["Title"] = "ChartHomeworkCount";
}
<h2><a asp-controller="Teacher" asp-action="TeacherTasks" class="btn btn-default">返回布置作业页面</a></h2>
@*<script src="http://cdn.hcharts.cn/jquery/jquery-1.8.3.min.js"></script>
    <script src="http://cdn.hcharts.cn/highcharts/highcharts.js"></script>*@
@*把地址上的代码复制到自己的项目里,就不用每次都需要联网才可以使用script了*@
<script src="~/js/jquery-1.8.3.min.js"></script>
<script src="~/js/highchartst.js"></script>
<div>
    <high-charts id="demoline" title="信息班各老师布置作业数量线图" subtitle="各种类数量统计" type="Line" series="ViewBag.Series"></high-charts>
    <high-charts id="democolumn" title="信息班各老师布置作业数量柱图" subtitle="各种类数量统计" type="Column" series="ViewBag.Series"></high-charts>
    <high-charts id="demopie" title="信息班各老师布置作业数量饼图" subtitle="各种类数量统计" type="Pie" series="ViewBag.Series"></high-charts>
</div>
View Code

 

第三步?当然是运行啦,看结果,似不似很牛X?

 

 ps:此文为本人整合别人的博客写的,若有冒犯之处,敬请原谅。只因本人是菜鸟,所以比大牛写的详细点,只供学习所用。

大牛LineZero's Blog的源项目:https://github.com/linezero/HighchartsNET

 

 

 

 

posted @ 2018-09-26 09:17  风葬秋暝  阅读(4687)  评论(5编辑  收藏  举报