Chart.js 是一套開放原始碼的「圖表」繪製函式庫,和其他第三方的圖表工具相比,Chart.js 的特色如下:

  • 支援 HTML 5、響應式網頁 (RWD, Responsive Web Design)
  • 可免費使用,且可作為商業用途
  • 開放原始碼 (GitHub)
  • 可用 JavaScript 操作及開發
  • 可與 JSON 格式整合,因此能與 ASP.NET MVC、ASP.NET WebAPI、AJAX 技術作整合,便於資料傳遞

圖 1 本文範例的執行畫面 (.html、.cshtml)

-------------------------------------------------
本文的 ASP.NET MVC 範例下載:
https://files.cnblogs.com/files/WizardWu/190101.zip
---------------------------------------------------

Chart.js 官方網站:
https://www.chartjs.org/

Chart.js 使用方式:
Visual Studio 中的引用方式,用 NuGet 安裝 Chart.js,並在頁面中引用 Chart.min.js。

----------------------------------------------------------------------------------------------------------------------------------------

以下的範例 1,以單純的 .html 來測試 Chart.js (不使用 .NET / C#)。資料來源,是寫死在頁面裡的 JavaScript。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title></title>
  6. <!--<link href="../Content/bootstrap.min.css" rel="stylesheet" />-->
  7. <script src="../Scripts/Chart.min.js"></script>
  8. </head>
  9. <body>
  10. <canvas id="myChart"></canvas>
  11.  
  12. <script>
  13. var ctx = document.getElementById("myChart");
  14. var chart = new Chart(ctx, {
  15. type: "line",
  16. data: {
  17. labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
  18. datasets: [{
  19. label: "台北",
  20. fill: false,
  21. backgroundColor: 'rgba(255,165,0,0.3)',
  22. borderColor: 'rgb(255,135,20)',
  23. pointStyle: "circle",
  24. pointBackgroundColor: 'rgb(0,222,0)',
  25. pointRadius: 5,
  26. pointHoverRadius: 10,
  27. data: [13.1, 10.2, 13.5, 20.9, 25.2, 27.1, 31.8]
  28. }, {
  29. label: "高雄",
  30. fill: false,
  31. backgroundColor: 'rgba(0,255,255,0.3)',
  32. borderColor: 'rgb(0,225,255)',
  33. pointStyle: "triangle",
  34. pointBackgroundColor: 'blue',
  35. pointRadius: 5,
  36. pointHoverRadius: 10,
  37. data: [29.1, 28.3, 22.6, 25.4, 27.5, 23.4]
  38.  
  39. }, {
  40. label: "越南",
  41. fill: false,
  42. backgroundColor: 'rgba(153,50,204,0.3)',
  43. borderColor: 'rgb(123,55,190)',
  44. pointStyle: "rect",
  45. pointBackgroundColor: 'rgb(220,20,60)',
  46. pointRadius: 5,
  47. pointHoverRadius: 10,
  48. data: [16.6, 17.3, 19.2, 23.8, 12.0, 17.6]
  49.  
  50. }]
  51. },
  52. options: {
  53. responsive: true,
  54. title: {
  55. display: true,
  56. fontSize: 26,
  57. text: '2019 年各分公司 1 - 6 月份營業額'
  58. },
  59. tooltips: {
  60. mode: 'point',
  61. intersect: true,
  62. },
  63. hover: {
  64. mode: 'nearest',
  65. intersect: true
  66. },
  67. scales: {
  68. xAxes: [{
  69. display: true,
  70. scaleLabel: {
  71. display: true,
  72. labelString: '月份',
  73. fontSize: 15
  74. },
  75. ticks: {
  76. fontSize: 15
  77. }
  78. }],
  79. yAxes: [{
  80. display: true,
  81. scaleLabel: {
  82. display: true,
  83. labelString: '百萬(美元)',
  84. fontSize: 15
  85. },
  86. ticks: {
  87. fontSize: 15
  88. }
  89. }]
  90. },
  91. animation: {
  92. duration: 2000
  93. }
  94. }
  95. });
  96. </script>
  97. </body>
  98. </html>

\htmlPages\LineChart.html

以下的範例 2,使用 ASP.NET MVC 來測試 Chart.js。

資料來源,取自 Controller 層 (C# Collection 轉成 JSON 格式)。亦可改成取自 WebAPI 或資料庫。

  1. using System.Web.Mvc;
  2. using ChartJS.Models;
  3. using Newtonsoft.Json;
  4. using Newtonsoft.Json.Linq;
  5.  
  6. namespace ChartJS.Controllers
  7. {
  8. public class BranchController : Controller
  9. {
  10. // GET: Branch
  11. public ActionResult Index()
  12. {
  13. return View();
  14. }
  15.  
  16. public ActionResult getBusinessJsonData()
  17. {
  18. string[] arrMonth = { "1月", "2月", "3月", "4月", "5月", "6月" };
  19.  
  20. //C# convert JSON string
  21. string jsonMonth = Newtonsoft.Json.JsonConvert.SerializeObject(arrMonth);
  22. ViewBag.JsonMonth = jsonMonth;
  23.  
  24. List<Branch> branchs = new List<Branch>
  25. {
  26. new Branch
  27. {
  28. City="台北",
  29. Business = new double[] { 13.1, 10.2, 13.5, 20.9, 25.2, 27.1, 31.8 }
  30. },
  31. new Branch{
  32. City="高雄",
  33. Business = new double[] { 29.1, 28.3, 22.6, 25.4, 27.5, 23.4 }
  34.  
  35. },
  36. new Branch{
  37. City="越南",
  38. Business = new double[] { 16.6, 17.3, 19.2, 23.8, 12.0, 17.6 }
  39. }
  40. };
  41.  
  42. //C# convert JSON string
  43. string jsonBusiness = Newtonsoft.Json.JsonConvert.SerializeObject(branchs);
  44. ViewBag.JsonBusiness = jsonBusiness;
  45.  
  46. //回傳 JSON 格式,讓各種 client 裝置,以 AJAX 方式呼叫的 API
  47. //return Json(branchs, JsonRequestBehavior.AllowGet);
  48.  
  49. return View(branchs);
  50. }
  51. }
  52. }

\Controllers\BranchController.cs

  1. @model IEnumerable<ChartJS.Models.Branch>
  2.  
  3. @{
  4. ViewBag.Title = "Chart.js 範例";
  5. }
  6. @*<h2>Index</h2>*@
  7.  
  8. <script src="../Scripts/Chart.min.js"></script>
  9.  
  10. <canvas id="myChart"></canvas>
  11.  
  12. <table>
  13. <!--從 Model 讀取 Business 資料-->
  14. @*@{ var js = new System.Web.Script.Serialization.JavaScriptSerializer(); }
  15.  
  16. @foreach (var m in Model)
  17. {
  18. <tr>
  19. <td>@Html.DisplayFor(x => m.City)</td>
  20. <td>@js.Serialize(m.Business)</td>
  21. </tr>
  22. }*@
  23. </table>
  24.  
  25. <script>
  26. //將 JSON 資料,指派給 JavaScript array
  27. //月份 (1月~6月)
  28. var jsMonth = @Html.Raw(ViewBag.JsonMonth);
  29.  
  30. //三個城市的 City、Business
  31. var jsBusiness = @Html.Raw(ViewBag.JsonBusiness);
  32.  
  33. var ctx = document.getElementById("myChart");
  34. var chart = new Chart(ctx, {
  35. type: "line",
  36. data: {
  37. //labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
  38. labels: jsMonth,
  39. datasets: [{
  40. //label: "台北",
  41. label: jsBusiness[0].City,
  42. fill: false,
  43. backgroundColor: 'rgba(255,165,0,0.3)',
  44. borderColor: 'rgb(255,135,20)',
  45. pointStyle: "circle",
  46. pointBackgroundColor: 'rgb(0,222,0)',
  47. pointRadius: 5,
  48. pointHoverRadius: 10,
  49. data: jsBusiness[0].Business
  50. //data: [13.1, 10.2, 13.5, 20.9, 25.2, 27.1, 31.8]
  51. }, {
  52. //label: "高雄",
  53. label: jsBusiness[1].City,
  54. fill: false,
  55. backgroundColor: 'rgba(0,255,255,0.3)',
  56. borderColor: 'rgb(0,225,255)',
  57. pointStyle: "triangle",
  58. pointBackgroundColor: 'blue',
  59. pointRadius: 5,
  60. pointHoverRadius: 10,
  61. data: jsBusiness[1].Business
  62. //data: [29.1, 28.3, 22.6, 25.4, 27.5, 23.4]
  63. }, {
  64. //label: "越南",
  65. label: jsBusiness[2].City,
  66. fill: false,
  67. backgroundColor: 'rgba(153,50,204,0.3)',
  68. borderColor: 'rgb(123,55,190)',
  69. pointStyle: "rect",
  70. pointBackgroundColor: 'rgb(220,20,60)',
  71. pointRadius: 5,
  72. pointHoverRadius: 10,
  73. data: jsBusiness[2].Business
  74. //data: [16.6, 17.3, 19.2, 23.8, 12.0, 17.6]
  75. }]
  76. },
  77. options: {
  78. responsive: true,
  79. title: {
  80. display: true,
  81. fontSize: 26,
  82. text: '2019 年各分公司 1 - 6 月份營業額'
  83. },
  84. tooltips: {
  85. mode: 'point',
  86. intersect: true,
  87. },
  88. hover: {
  89. mode: 'nearest',
  90. intersect: true
  91. },
  92. scales: {
  93. xAxes: [{
  94. display: true,
  95. scaleLabel: {
  96. display: true,
  97. labelString: '月份',
  98. fontSize: 15
  99. },
  100. ticks: {
  101. fontSize: 15
  102. }
  103. }],
  104. yAxes: [{
  105. display: true,
  106. scaleLabel: {
  107. display: true,
  108. labelString: '百萬(美元)',
  109. fontSize: 15
  110. },
  111. ticks: {
  112. fontSize: 15
  113. }
  114. }]
  115. },
  116. animation: {
  117. duration: 2000
  118. }
  119. }
  120. });
  121. </script>

\Views\Branch\getBusinessJsonData.cshtml

----------------------------------------------------------------------------------------------------------------------------------------
參考資料:

[1] Chart.js 官方網站
https://www.chartjs.org/samples/latest/
https://www.chartjs.org/docs/latest/

[2] ASP.NET Web API (msdn)
https://docs.microsoft.com/zh-tw/aspnet/web-api/

----------------------------------------------------------------------------------------------------------------------------------------
參考書籍:

[1] 網頁程式設計 ASP.NET MVC 5.x 範例完美演繹 (繁體書籍), Ch 5、Ch 6, 作者:奚江華
https://www.tenlong.com.tw/products/9789864769292?list_name=srh

[2] 跟著實務學習 ASP.NET MVC (繁體書籍), 作者:蔡文龍、蔡捷雲、歐志信、曾芷琳、萬鴻曜
https://www.tenlong.com.tw/products/9789864766918?list_name=srh

----------------------------------------------------------------------------------------------------------------------------------------

Chart.js 與 ASP.NET MVC 整合應用的更多相关文章

  1. 我的博客:C# PHP J2ee Java Android js WP Asp.net mvc Python

    <p><A target="_blank" href="http://blog.163.com/hr_company_product/" &g ...

  2. 基于Bootstrap和Knockout.js的ASP.NET MVC开发实战

    之前在一家公司里用过Knockout,是easyui 和 Knockout结合 的.下面的这本应该不错. 目录 前言 第一部分入门指南 第1章MVC介绍 创建第一个项目 分析HomeControlle ...

  3. 用JS解决Asp.net Mvc返回JsonResult中DateTime类型数据格式的问题

    当用ajax异步时,返回JsonResult格式的时候,发现当字段是dateTime类型时,返回的json格式既然是“/Date(1435542121135)/” 这样子的,当然这不是我们想要的格式. ...

  4. asp.net mvc整合Nhibernate的配置方法

    http://blog.csdn.net/xz2001/article/details/8452794 http://www.cnblogs.com/GoodHelper/archive/2011/0 ...

  5. 基于Bootstrap和Knockout.js的ASP.NET MVC开发实战 关于 拦截器的 学习 部分

    先贴一段: 下面贴代码: 上面这段代码呢,有几个点迷糊.可以找找看

  6. ASP.NET MVC 單元測試系列

    ASP.NET MVC 單元測試系列 (7):Visual Studio Unit Test 透過 Visual Studio 裡的整合開發環境 (IDE) 結合單元測試開發是再便利不過的了,在 Vi ...

  7. 基于TeamCity的asp.net mvc/core,Vue 持续集成与自动部署

    一 Web Server(Windows)端的配置 1.配置IIS,重要的是管理服务 1.1 配置FTP(前端NPM项目需要) 该步骤略,如果是在阿里云ESC上,需要开启端口21(用来FTP认证握手) ...

  8. asp.net mvc中的后台验证

    asp.net mvc的验证包含后台验证和前端验证.后台验证主要通过数据注解的形式实现对model中属性的验证,其验证过程发生在model绑定的过程中.前端验证是通过结合jquery.validate ...

  9. ASP.NET MVC异步验证是如何工作的02,异步验证表单元素的创建

    在上一篇"ASP.NET MVC异步验证是如何工作的01,jQuery的验证方式.错误信息提示.validate方法的背后"中,了解了jQuery如何验证,如何显示错误信息,本篇要 ...

随机推荐

  1. ES 12 - 配置使用Elasticsearch的动态映射 (dynamic mapping)

    目录 1 动态映射(dynamic mapping) 1.1 什么是动态映射 1.2 体验动态映射 1.3 搜索结果不一致的原因分析 2 开启dynamic mapping策略 2.1 约束策略 2. ...

  2. 学习 JavaScript(二)在 HTML 中使用 JS

    基本用法 在 HTML 中使用 <script> 元素引入 Javascript , <script> 有以下 4 个常用属性: async: 异步加载,只对外部脚步有效. d ...

  3. [翻译 EF Core in Action 1.8] MyFirstEfCoreApp应用程序设置

    Entity Framework Core in Action Entityframework Core in action是 Jon P smith 所著的关于Entityframework Cor ...

  4. “==”、“equals()”、“hashcode()”之间的秘密

    前言 万丈高楼平地起,今天的聊点基础而又经常让人忽视的话题,比如“==”与“equals()”区别?为何当我们重写完"equals()"后也要有必要去重写"hashcod ...

  5. js防抖和节流

    今天在网上看到的,里面的内容非常多.说下我自己的理解. 所谓的防抖就是利用延时器来使你的最后一次操作执行.而节流是利用时间差的办法,每一段时间执行一次.下面是我的代码: 这段代码是右侧的小滑块跟随页面 ...

  6. 安卓开发笔记(二十五):ViewPager的使用

    首先我们来看看运行之后的效果: 然后我们也不多说废话了,下面是这个项目所需要的全部代码,很多博主写这个都不把代码写完,因此笔者自己也琢磨了一会儿才把这个弄出来,感觉很烦,但我肯定会把代码写全的.我这里 ...

  7. Maven 基本的认识

    Maven 基本的认识 1. 什么是Maven? 在平时开发中,经常遇到某个jar包,我在代码层已经Import 和@Automation了,编译器还是提醒你某个jar包找不到,往往这时来个mvn i ...

  8. Doskey命令详解

    转自:https://blog.csdn.net/u012993732/article/details/48626921 调用 Doskey.exe,它撤回 Windows XP 命令.编辑命令行并创 ...

  9. C# Npoi 实现Excel与数据库相互导入

    十年河东,十年河西,莫欺少年穷! NPOI支持对 Word 和 Excel 文件的操作! 针对 Word 的操作一般用于打印技术!说白了就是利用 Word 文件作为模板,生成各种不同的打印!具体用到的 ...

  10. AI - 深度学习之美十四章-概念摘要(8~14)

    原文链接:https://yq.aliyun.com/topic/111 本文是对原文内容中部分概念的摘取记录,可能有轻微改动,但不影响原文表达. 08 - BP算法双向传,链式求导最缠绵 反向传播( ...