Chart.js 與 ASP.NET MVC 整合應用
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。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!--<link href="../Content/bootstrap.min.css" rel="stylesheet" />-->
<script src="../Scripts/Chart.min.js"></script>
</head>
<body>
<canvas id="myChart"></canvas> <script>
var ctx = document.getElementById("myChart");
var chart = new Chart(ctx, {
type: "line",
data: {
labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
datasets: [{
label: "台北",
fill: false,
backgroundColor: 'rgba(255,165,0,0.3)',
borderColor: 'rgb(255,135,20)',
pointStyle: "circle",
pointBackgroundColor: 'rgb(0,222,0)',
pointRadius: 5,
pointHoverRadius: 10,
data: [13.1, 10.2, 13.5, 20.9, 25.2, 27.1, 31.8]
}, {
label: "高雄",
fill: false,
backgroundColor: 'rgba(0,255,255,0.3)',
borderColor: 'rgb(0,225,255)',
pointStyle: "triangle",
pointBackgroundColor: 'blue',
pointRadius: 5,
pointHoverRadius: 10,
data: [29.1, 28.3, 22.6, 25.4, 27.5, 23.4] }, {
label: "越南",
fill: false,
backgroundColor: 'rgba(153,50,204,0.3)',
borderColor: 'rgb(123,55,190)',
pointStyle: "rect",
pointBackgroundColor: 'rgb(220,20,60)',
pointRadius: 5,
pointHoverRadius: 10,
data: [16.6, 17.3, 19.2, 23.8, 12.0, 17.6] }]
},
options: {
responsive: true,
title: {
display: true,
fontSize: 26,
text: '2019 年各分公司 1 - 6 月份營業額'
},
tooltips: {
mode: 'point',
intersect: true,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: '月份',
fontSize: 15
},
ticks: {
fontSize: 15
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: '百萬(美元)',
fontSize: 15
},
ticks: {
fontSize: 15
}
}]
},
animation: {
duration: 2000
}
}
});
</script>
</body>
</html>
\htmlPages\LineChart.html
以下的範例 2,使用 ASP.NET MVC 來測試 Chart.js。
資料來源,取自 Controller 層 (C# Collection 轉成 JSON 格式)。亦可改成取自 WebAPI 或資料庫。
using System.Web.Mvc;
using ChartJS.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq; namespace ChartJS.Controllers
{
public class BranchController : Controller
{
// GET: Branch
public ActionResult Index()
{
return View();
} public ActionResult getBusinessJsonData()
{
string[] arrMonth = { "1月", "2月", "3月", "4月", "5月", "6月" }; //C# convert JSON string
string jsonMonth = Newtonsoft.Json.JsonConvert.SerializeObject(arrMonth);
ViewBag.JsonMonth = jsonMonth; List<Branch> branchs = new List<Branch>
{
new Branch
{
City="台北",
Business = new double[] { 13.1, 10.2, 13.5, 20.9, 25.2, 27.1, 31.8 }
},
new Branch{
City="高雄",
Business = new double[] { 29.1, 28.3, 22.6, 25.4, 27.5, 23.4 } },
new Branch{
City="越南",
Business = new double[] { 16.6, 17.3, 19.2, 23.8, 12.0, 17.6 }
}
}; //C# convert JSON string
string jsonBusiness = Newtonsoft.Json.JsonConvert.SerializeObject(branchs);
ViewBag.JsonBusiness = jsonBusiness; //回傳 JSON 格式,讓各種 client 裝置,以 AJAX 方式呼叫的 API
//return Json(branchs, JsonRequestBehavior.AllowGet); return View(branchs);
}
}
}
\Controllers\BranchController.cs
@model IEnumerable<ChartJS.Models.Branch>
@{
ViewBag.Title = "Chart.js 範例";
}
@*<h2>Index</h2>*@
<script src="../Scripts/Chart.min.js"></script>
<canvas id="myChart"></canvas>
<table>
<!--從 Model 讀取 Business 資料-->
@*@{ var js = new System.Web.Script.Serialization.JavaScriptSerializer(); }
@foreach (var m in Model)
{
<tr>
<td>@Html.DisplayFor(x => m.City)</td>
<td>@js.Serialize(m.Business)</td>
</tr>
}*@
</table>
<script>
//將 JSON 資料,指派給 JavaScript array
//月份 (1月~6月)
var jsMonth = @Html.Raw(ViewBag.JsonMonth);
//三個城市的 City、Business
var jsBusiness = @Html.Raw(ViewBag.JsonBusiness);
var ctx = document.getElementById("myChart");
var chart = new Chart(ctx, {
type: "line",
data: {
//labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
labels: jsMonth,
datasets: [{
//label: "台北",
label: jsBusiness[0].City,
fill: false,
backgroundColor: 'rgba(255,165,0,0.3)',
borderColor: 'rgb(255,135,20)',
pointStyle: "circle",
pointBackgroundColor: 'rgb(0,222,0)',
pointRadius: 5,
pointHoverRadius: 10,
data: jsBusiness[0].Business
//data: [13.1, 10.2, 13.5, 20.9, 25.2, 27.1, 31.8]
}, {
//label: "高雄",
label: jsBusiness[1].City,
fill: false,
backgroundColor: 'rgba(0,255,255,0.3)',
borderColor: 'rgb(0,225,255)',
pointStyle: "triangle",
pointBackgroundColor: 'blue',
pointRadius: 5,
pointHoverRadius: 10,
data: jsBusiness[1].Business
//data: [29.1, 28.3, 22.6, 25.4, 27.5, 23.4]
}, {
//label: "越南",
label: jsBusiness[2].City,
fill: false,
backgroundColor: 'rgba(153,50,204,0.3)',
borderColor: 'rgb(123,55,190)',
pointStyle: "rect",
pointBackgroundColor: 'rgb(220,20,60)',
pointRadius: 5,
pointHoverRadius: 10,
data: jsBusiness[2].Business
//data: [16.6, 17.3, 19.2, 23.8, 12.0, 17.6]
}]
},
options: {
responsive: true,
title: {
display: true,
fontSize: 26,
text: '2019 年各分公司 1 - 6 月份營業額'
},
tooltips: {
mode: 'point',
intersect: true,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: '月份',
fontSize: 15
},
ticks: {
fontSize: 15
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: '百萬(美元)',
fontSize: 15
},
ticks: {
fontSize: 15
}
}]
},
animation: {
duration: 2000
}
}
});
</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 整合應用的更多相关文章
- 我的博客:C# PHP J2ee Java Android js WP Asp.net mvc Python
<p><A target="_blank" href="http://blog.163.com/hr_company_product/" &g ...
- 基于Bootstrap和Knockout.js的ASP.NET MVC开发实战
之前在一家公司里用过Knockout,是easyui 和 Knockout结合 的.下面的这本应该不错. 目录 前言 第一部分入门指南 第1章MVC介绍 创建第一个项目 分析HomeControlle ...
- 用JS解决Asp.net Mvc返回JsonResult中DateTime类型数据格式的问题
当用ajax异步时,返回JsonResult格式的时候,发现当字段是dateTime类型时,返回的json格式既然是“/Date(1435542121135)/” 这样子的,当然这不是我们想要的格式. ...
- asp.net mvc整合Nhibernate的配置方法
http://blog.csdn.net/xz2001/article/details/8452794 http://www.cnblogs.com/GoodHelper/archive/2011/0 ...
- 基于Bootstrap和Knockout.js的ASP.NET MVC开发实战 关于 拦截器的 学习 部分
先贴一段: 下面贴代码: 上面这段代码呢,有几个点迷糊.可以找找看
- ASP.NET MVC 單元測試系列
ASP.NET MVC 單元測試系列 (7):Visual Studio Unit Test 透過 Visual Studio 裡的整合開發環境 (IDE) 結合單元測試開發是再便利不過的了,在 Vi ...
- 基于TeamCity的asp.net mvc/core,Vue 持续集成与自动部署
一 Web Server(Windows)端的配置 1.配置IIS,重要的是管理服务 1.1 配置FTP(前端NPM项目需要) 该步骤略,如果是在阿里云ESC上,需要开启端口21(用来FTP认证握手) ...
- asp.net mvc中的后台验证
asp.net mvc的验证包含后台验证和前端验证.后台验证主要通过数据注解的形式实现对model中属性的验证,其验证过程发生在model绑定的过程中.前端验证是通过结合jquery.validate ...
- ASP.NET MVC异步验证是如何工作的02,异步验证表单元素的创建
在上一篇"ASP.NET MVC异步验证是如何工作的01,jQuery的验证方式.错误信息提示.validate方法的背后"中,了解了jQuery如何验证,如何显示错误信息,本篇要 ...
随机推荐
- asp.net core系列 57 IS4 使用混合流(OIDC+OAuth2.0)添加API访问
一.概述 在上篇中,探讨了交互式用户身份验证,使用的是OIDC协议. 在之前篇中对API访问使用的是OAuth2.0协议.这篇把这两个部分放在一起,OpenID Connect和OAuth 2.0组合 ...
- Spring boot 继承 阿里 autoconfig 配置环境参数
前提:基于springboot 项目 1. 配置pom.xml 文件 <plugin> <groupId>com.alibaba.citrus.tool</groupId ...
- 十问 JVM
今天我们来讨论下 Java 虚拟机,通过一系列常见的问题来逐渐深入了解 JVM 创建对象过程,内存布局,类加载以及 GC 回收算法等机制. 十问 JVM 问题整理: Java虚拟机创建对象的过程 (使 ...
- 前端笔记之ES678&Webpack&Babel(中)对象|字符串|数组的扩展&函数新特性&类
一.对象的扩展 1.1对象属性名表达式 ES6可以在JSON中使用[]包裹一个key的名字.此时这个key将用表达式作为属性名(被当做变量求值),这个key值必须是字符串. var a = 'name ...
- .Net Core使用Redis(CSRedis)
前言 CSRedis是国外大牛写的.git地址:https://github.com/2881099/csredis,让我们看看如果最简单的 使用一下CSRedis吧. 引入NuGet 获取Nuget ...
- Wmyskxz文章目录导航附Java精品学习资料
前言:这段时间一直在准备校招的东西,所以一晃眼都好长时间没更新了,这段时间准备的稍微好那么一点点,还是觉得准备归准备,该有的学习节奏还是要有..趁着复习的空隙来整理整理自己写过的文章吧..好多加了微信 ...
- 使用 HttpRequester 更方便的发起 HTTP 请求
使用 HttpRequester 更方便的发起 HTTP 请求 Intro 一直感觉 .net 里面(这里主要说的是 .net framework 下)发送 HTTP 请求的方式用着不是特别好用,而且 ...
- python3 完全理解赋值,浅copy,深copy 通过地址详细理解~
额...老规矩,先来一天NLP再说,也没几条了. 十,在任何一个系统里,最灵活的部分是最能影响大局的部分 灵活便是有一个以上的选择,选择便是能力,因此最灵活的人便是最有能力的人. 灵活来自减少只相信自 ...
- 【重磅】微软开源自动机器学习工具 - NNI
[重磅]微软开源自动机器学习工具 - NNI 在机器学习建模时,除了准备数据,最耗时耗力的就是尝试各种超参组合,找到模型最佳效果的过程了.即使是对于有经验的算法工程师和数据科学家,有时候也很难把握其中 ...
- C++ 最简单的日志类
最近搞一个 C++ 项目的二次开发,没玩过 C++,可谓步履维艰.自己写个简单的日志类都被各种坑折磨.终于搞定了. 参考了这篇博客,并且进一步简化:https://www.cnblogs.com/Ds ...