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://github.com/linezero/HighchartsNET
?
代碼遷移升級
首先我們新建一個 .NET Core Class Library ->?HighchartsNETCore
然后我們添加引用
Install-Package Microsoft.AspNetCore.Razor.Runtime
新建一個HighChartsTagHelper.cs然后將之前的?HighCharts.cs 的代碼復制到其中,進行相關更改。
這里首先需要引用?using Microsoft.AspNetCore.Razor.TagHelpers; 然后繼承?TagHelper 重寫 Process。
在之前的屬性上加上?HtmlAttributeName 特性,調整方法。
最終主要代碼如下:
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());
? ? ? ? }
? ? }
TagHelper 使用
代碼編寫好以后,新建一個 ASP.NET Core Web Application 名為 HighchartsNETCoreWeb -> 選擇Web應用程序-》不進行身份驗證。
添加?HighchartsNETCore 引用。
然后打開 Views/_ViewImports.cshtml 文件添加:
@using HighchartsNETCoreWeb @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers@addTagHelper *,HighchartsNETCore然后將 Home/Index.cshtml 替換為如下代碼:
<script src="http://cdn.hcharts.cn/jquery/jquery-1.8.3.min.js"></script><script src="http://cdn.hcharts.cn/highcharts/highcharts.js"></script> <div><high-charts id="demoline" title="ASP.NET Core 線圖" subtitle="http://www.cnblogs.com/linezero" type="Line" series="ViewBag.Series"></high-charts><high-charts id="democolumn" title="ASP.NET Core柱圖" subtitle="http://www.cnblogs.com/linezero" type="Column" series="ViewBag.Series"></high-charts><high-charts id="demopie" title="ASP.NET Core餅圖" subtitle="http://www.cnblogs.com/linezero" type="Pie" series="ViewBag.Series"></high-charts> </div>在Index Action添加數據源
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();}
運行程序?http://localhost:5000/
?
?
更多使用示例可以參考以前的Web 文件夾。
將HighchartsNETCore 打包以后可以直接適用于任意ASP.NET Core MVC應用程序。
原文鏈接: http://www.cnblogs.com/linezero/p/HighchartsMVCTagHelper.html
.NET社區新聞,深度好文,微信中搜索dotNET跨平臺或掃描二維碼關注
總結
以上是生活随笔為你收集整理的ASP.NET Core MVC TagHelper实践HighchartsNET快速图表控件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Autofac 之 基于 Castle
- 下一篇: 使用StyleCop 进行代码评审