You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core MVC中正确实现Chart.js?呼叫状态环形图不显示

问题排查与解决方案

核心问题分析

你的图表无法显示,主要有三个关键原因:

  1. 未引入Chart.js库:浏览器无法识别Chart构造函数,导致图表初始化失败;
  2. Razor生成JS时的语法错误:字符串未加引号,引发JS执行中断;
  3. 额外优化点:前端循环统计数据效率低且易出错,建议后端提前完成统计。

修正步骤

1. 优化控制器代码(后端统计数据)

将统计逻辑移到后端,直接计算各状态的呼叫数量,减少前端复杂度:

public async Task<IActionResult> GetAllCalls()
{
    ReceivedCallModel model = new ReceivedCallModel();
    var request = new HttpRequestMessage(HttpMethod.Get, $"https://api.twilio.com/2010-04-01/Accounts/{Account_Sid}/Calls.json?StartTime=2023-06-22");
    var client = _httpClientFactory.CreateClient("MyClient");
    HttpResponseMessage response = await client.SendAsync(request);
    
    if(response.StatusCode == HttpStatusCode.OK)
    {
        var jsonString = await response.Content.ReadAsStringAsync();
        model = JsonConvert.DeserializeObject<ReceivedCallModel>(jsonString);
        
        // 统计外呼呼叫各状态数量
        var callStats = model.calls
            .Where(call => call.direction == "outbound-api")
            .GroupBy(call => call.status)
            .ToDictionary(g => g.Key, g => g.Count());
        
        // 给ViewBag赋值,默认0避免undefined
        ViewBag.CompletedCount = callStats.TryGetValue("completed", out int completed) ? completed : 0;
        ViewBag.NoAnswerCount = callStats.TryGetValue("no-answer", out int noAnswer) ? noAnswer : 0;
        ViewBag.BusyCount = callStats.TryGetValue("busy", out int busy) ? busy : 0;
        ViewBag.FailedCount = callStats.TryGetValue("failed", out int failed) ? failed : 0;
        
        TempData["success"] = "Successful";
    }
    return View(model);
}

2. 修正视图代码(引入Chart.js + 简化前端逻辑)

确保引入Chart.js库,并直接使用后端统计好的数据初始化图表:

@model ReceivedCallModel
<div class="container">
    <div class="row justify-content-center">
        <div class="col-sm-6">
            <div class="card border-0">
                <div class="card-body">
                    <canvas id="chart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

@section Scripts{
    <!-- 引入Chart.js库 -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script type="text/javascript">
        // 获取canvas上下文
        const ctx = document.getElementById('chart').getContext('2d');
        
        // 初始化环形图
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['completed', 'no-answer', 'busy', 'failed'],
                datasets: [{
                    label: 'Call Status',
                    data: [
                        @ViewBag.CompletedCount,
                        @ViewBag.NoAnswerCount,
                        @ViewBag.BusyCount,
                        @ViewBag.FailedCount
                    ],
                    backgroundColor: [
                        'rgb(20, 205, 86)',
                        'rgb(54, 162, 235)',
                        'rgb(255, 205, 86)',
                        'rgb(255,0,0)'
                    ],
                    hoverOffset: 4
                }]
            }
        });
    </script>
}

关键修正说明

  • 引入Chart.js:这是图表不显示的核心原因,必须先加载库才能识别Chart对象;
  • 后端统计数据:避免前端循环统计的冗余代码,同时消除了字符串未加引号导致的JS语法错误;
  • 默认值处理:使用TryGetValue确保各状态数量默认值为0,避免图表数据出现undefined。

内容的提问来源于stack exchange,提问作者Earlingh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 22:32:03