Chart.js 與 ASP.NET MVC 整合應用

时间:2023-02-25 07:49:31

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

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

Chart.js 與 ASP.NET MVC 整合應用

圖 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 整合應用的更多相关文章

  1. 我的博客:C&num; PHP J2ee Java Android js WP Asp&period;net mvc Python

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

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

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

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

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

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

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

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

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

  6. ASP&period;NET MVC 單元測試系列

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

  7. 基于TeamCity的asp&period;net mvc&sol;core&comma;Vue 持续集成与自动部署

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

  8. asp&period;net mvc中的后台验证

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

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

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

随机推荐

  1. Setting Up KeePass For Centos 6

    This mini-howto describes how to set up KeePass on Centos 6. It requires building mono from source a ...

  2. POJ 3669 Meteor Shower(流星雨)

    POJ 3669 Meteor Shower(流星雨) Time Limit: 1000MS    Memory Limit: 65536K Description 题目描述 Bessie hears ...

  3. 20145305 《Java程序设计》实验四

    Android开发基础 安装过程没有截图 给出安装参考链接 http://ask.android-studio.org/?/article/9 实验结果截图: 完成HelloWorld项目,显示自己的 ...

  4. JAX-RS -- Java API for RESTful Web Services

    Java EE 6 引入了对 JSR-311 的支持.JSR-311(JAX-RS:Java API for RESTful Web Services)旨在定义一个统一的规范,使得 Java 程序员可 ...

  5. 64位win7安装jdk和eclipse

    本人正确安装成功步骤,对他人可能无用: 1.直接拷以前32位eclipse ADT 2.安装32位的jdk:jdk-8u45-windows-i586 3.ok,所有环境变量无需手工设置 eclips ...

  6. netstat和net命令粗谈

    网络连接查看命令netstat netstat -a 查看开启了哪些端口,常用netstat -an netstat -n 查看端口的网络连接情况,常用netstat -an netstat -v 查 ...

  7. Unix和Windows文件格式转化

    可能的原因有: 1)执行权限的问题 解决方法: chmod +x ***.py 2)python版本的问题 解决方法:在执行时或者在py文件中选择好对应的Python的版本 3)python文件格式的 ...

  8. cifar数据集介绍及到图像转换的实现

    CIFAR是一个用于普通物体识别的数据集.CIFAR数据集分为两种:CIFAR-10和CIFAR-100.The CIFAR-10 and CIFAR-100 are labeled subsets ...

  9. console&period;dir&lpar;someObject&rpar;&semi;

    <script type="text/javascript"> function test(){ var array = [{"id":1},{&q ...

  10. 使用 Maven 管理项目

    最近的练手项目使用的是 Maven 在管理项目,在使用 Maven 管理项目时,三层的开发时分模块开发的,parent-dao-service-web,所有的spring+struts + Hiber ...