ASP.NET Core Razor融合JS库Demo

发布时间 2024-01-01 11:16:58作者: JohnYang819

cshtml.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorTest.Pages
{
    public class PrivacyModel : PageModel
    {
        public string TestStr { get; set; }
        public List<string> ItemList { get; set; }
        private readonly ILogger<PrivacyModel> _logger;
        public List<int> DataPoints { get; set; }
        public PrivacyModel(ILogger<PrivacyModel> logger)
        {
            _logger = logger;
        }

        public void OnGet()
        {
            TestStr = "JohnYang";
            ItemList = new List<string>
            {
                "apple","banana","火龙果"
            };
            DataPoints = new List<int> { 10, 20, 30, 40, 50 };
        }
    }

}

cshtml

@page
@model PrivacyModel
@{
    ViewData["Title"] = "Privacy Policy";
}

@* <script src="https://cdn.staticfile.org/Chart.js/3.9.1/chart.js"></script> *@//CDN
<script src="~/lib//chartjs/chart.js"></script> //下载到本地

<h1>@ViewData["Title"]</h1>
<p>JohnYangStr is @Model.TestStr</p>
<h1>Item List</h1>

<ul>
    @foreach (var item in Model.ItemList)
    {
        <li>@item</li>
    }
</ul>
<p>Use this page to detail your site's privacy policy.</p>
<canvas id="myChart" width="400" height="200"></canvas>

<script>
    // 获取 Razor 页面中的数据
    var dataPoints = @Html.Raw(Json.Serialize(Model.DataPoints));

    // 使用 Chart.js 创建图表
    var ctx = document.getElementById('myChart').getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: dataPoints.map((_, index) => `Label ${index + 1}`),
            datasets: [{
                label: 'My Chart',
                data: dataPoints,
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                borderColor: 'rgba(75, 192, 192, 1)',
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
</script>