以下是一个简化的示例,展示了如何在Asp.net Core MVC项目中使用jQuery的AJAX方法获取数据,并使用Chart.js绘制柱状图和饼图。
- 安装Chart.js NuGet包:
Install-Package ChartJs.Blazor.ChartJs
- 在\_ViewImports.cshtml中注册Chart.js组件:
@addTagHelper *, ChartJs.Blazor
- 在视图(View)中添加图表:
<canvas id="barChart"></canvas>
<canvas id="pieChart"></canvas>
@section Scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<script>
$(document).ready(function () {
fetchData();
});
function fetchData() {
$.ajax({
url: '@Url.Action("GetChartData", "Home")',
type: 'GET',
dataType: 'json',
success: function (data) {
drawBarChart(data.barData);
drawPieChart(data.pieData);
},
error: function (error) {
console.log(error);
}
});
}
function drawBarChart(data) {
var ctx = document.getElementById('barChart').getContext('2d');
var myBarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: data.labels,
datasets: [{
label: '数据集 1',
data: data.values,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}