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

}

}

}

新建一个名为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();

}

}

}

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

@using lwz

@using lwz.Models

@using lwz.Date

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@addTagHelper *,HighchartsNETCore

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

@{

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>*@

@*把地址上的代码复制到自己的项目wwwroot里,就不用每次都需要联网才可以使用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>

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

ps:此文为本人整合别人的博客写的,只供学习所用。请尊重别人的知识产权。

原文地址:https://www.cnblogs.com/fzqm-lwz/p/9704973.html

时间: 2024-10-15 20:31:15

Asp.NET Core制作图表的相关文章

在Linux和Windows的Docker容器中运行ASP.NET Core

(此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 译者序:其实过去这周我都在研究这方面的内容,结果周末有事没有来得及总结为文章,Scott Hanselman就捷足先登了.那么我就来翻译一下这篇文章,让更多的中文读者看到.当然Scott遇到的坑我也遇到了. 不过首先,对于不熟悉的朋友我还是来解释一下Linux容器和Windows容器的概念. 由于容器成为虚拟化和应用托管的一种不可避免的选项,Windows也开始为公众提供容器功能(其实微软具备和使用

Docker容器中运行ASP.NET Core

在Linux和Windows的Docker容器中运行ASP.NET Core 译者序:其实过去这周我都在研究这方面的内容,结果周末有事没有来得及总结为文章,Scott Hanselman就捷足先登了.那么我就来翻译一下这篇文章,让更多的中文读者看到.当然Scott遇到的坑我也遇到了. 不过首先,对于不熟悉的朋友我还是来解释一下Linux容器和Windows容器的概念. 由于容器成为虚拟化和应用托管的一种不可避免的选项,Windows也开始为公众提供容器功能(其实微软具备和使用容器技术很久了).这

ASP.NET Core MVC TagHelper实践HighchartsNET快速图表控件-开源

ASP.NET Core MVC TagHelper最佳实践HighchartsNET快速图表控件支持ASP.NET Core. 曾经在WebForms上写过 HighchartsNET快速图表控件-开源 Highcharts的ASP.NET Web自定义控件. 今天我就来改造它,将其使用最新的TagHelper 来实践,学习TagHelper 的使用也提供一个方便的图表控件在ASP.NET Core MVC中使用. 下面正式开始,使用之前的代码直接进行迁移升级. GitHub:https://

asp.net core 拦击器制作的权限管理系统DEMO

效果图 没有登陆不会执行请求日期的方法,不管是否登陆都不允许访问请求时间方法 验证不通过是会进行转发到Home/error方法中, 唯一有点遗憾的是会进行两次请求,而不是一次. 代码附上: [Route("[controller]/[action]")] public class HomeController : BaseController { /// <summary> /// Ajax请求页面 /// </summary> /// <param na

VS code docker 调试 asp.net core

前言 .net core的诞生就是为了解决跨平台的事情的,所以.net core app运行在linux.macOS.docker上也不是什么新鲜事了. 相信已经有不少.net core的项目已经部署在docker或者linux的环境下.但是一般的开发人员的开发环境不会是Ubuntu.redhat什么的,既然开发环境和部署环境的区别比较大,我们总希望在开发调试的时候,能更加贴近实际的部署环境.所以今天这篇文章说一下如何调试部署在docker的asp.net core app. 如果大家有安装VS

丙申年把真假美猴王囚禁在容器中跑 ASP.NET Core 1.0

丙申年把真假美猴王囚禁在容器中跑 ASP.NET Core 1.0? 警告 您当前查看的页面是未经授权的转载! 如果当前版本排版错误,请前往查看最新版本:http://www.cnblogs.com/qin-nz/p/aspnetcore-run-on-mono-in-year-of-monkey.html 提示 更新时间:2016年02月07日. 各位程序媛/程序猿们,猴年快乐. 相信不少媛/猿都是被标题吸引来的,那我我先解释下标题. 提示 本文是一篇半科普文,不对技术细节进行深入探究. 标题

ASP.NET Core开发-后台任务利器Hangfire使用

ASP.NET Core开发系列之后台任务利器Hangfire 使用. Hangfire 是一款强大的.NET开源后台任务利器,无需Windows服务/任务计划程序. 可以使用于ASP.NET 应用也可以使用于控制台.Hangfire 只需简单几句代码即可创建新的不同种类的任务. 目前 Hangfire 已经支持.NET Core ,现在就给大家讲解下在ASP.NET Core 里的使用. Hangfire GitHub:https://github.com/HangfireIO/Hangfir

Asp.Net Core 项目实战之权限管理系统(1) 使用AdminLTE搭建前端

参考页面: http://www.yuanjiaocheng.net/ASPNET-CORE/mvc-design-pattern.html http://www.yuanjiaocheng.net/ASPNET-CORE/mvc-routing.html http://www.yuanjiaocheng.net/ASPNET-CORE/attribute-route.html http://www.yuanjiaocheng.net/ASPNET-CORE/core-actionresults

ASP.NET Core 1.0 开发记录

参考页面: http://www.yuanjiaocheng.net/ASPNET-CORE/first.html http://www.yuanjiaocheng.net/ASPNET-CORE/asp-net-core-overview.html http://www.yuanjiaocheng.net/ASPNET-CORE/asp.net-core-environment.html http://www.yuanjiaocheng.net/ASPNET-CORE/newproject.h