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:此文為本人整合別人的博客寫的,只供學習所用。請尊重別人的知識產權。
Asp.NET Core制作圖表