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

在Blazor应用的Razor页面中集成Google Charts的技术咨询

Blazor集成Google Charts实操指南

1. 脚本部署位置

  • Google Charts核心加载脚本(<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>):
    • Blazor WebAssembly项目:放在wwwroot/index.html的<head>末尾或</body>标签前;
    • Blazor Server项目:放在Pages/_Layout.cshtml的对应位置。
  • 自定义绘制逻辑脚本:
    • 仅单页面使用:直接写在目标Razor页面的@section Scripts块中(Server项目),或通过IJSRuntime动态注入;
    • 多页面复用:放在wwwroot/js目录下的独立JS文件(如google-charts-helper.js),再在index.html/_Layout.cshtml中引入该文件。

2. 从Razor页面调用脚本

  1. 注入JS运行时服务:在Razor页面顶部添加
@inject IJSRuntime JS
  1. 在DOM渲染完成后调用脚本(用OnAfterRenderAsync生命周期方法):
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        // 加载Google Charts核心包
        await JS.InvokeVoidAsync("google.charts.load", "current", new { packages = new[] { "corechart" } });
        // 调用自定义绘制函数
        await JS.InvokeVoidAsync("drawChart");
    }
}
  1. 添加图表渲染容器:在Razor页面的HTML部分加入
<div id="chart-container" style="width: 800px; height: 400px;"></div>
  1. 自定义绘制脚本示例(以饼图为例):
function drawChart() {
    const data = google.visualization.arrayToDataTable([
        ['Activity', 'Hours'],
        ['Work', 11],
        ['Eat', 2],
        ['Sleep', 7]
    ]);

    const options = { title: 'Daily Activities' };
    const chart = new google.visualization.PieChart(document.getElementById('chart-container'));
    chart.draw(data, options);
}

3. 向脚本传递数据

通过IJSRuntime的调用参数直接传递Blazor端数据,JS端接收后转换为Google Charts所需格式:

  1. Blazor端准备数据并传递:
// 定义数据模型
public class ChartItem
{
    public string Name { get; set; }
    public int Value { get; set; }
}

// 页面数据
private List<ChartItem> _chartData = new()
{
    new ChartItem { Name = "Work", Value = 11 },
    new ChartItem { Name = "Eat", Value = 2 },
    new ChartItem { Name = "Sleep", Value = 7 }
};

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await JS.InvokeVoidAsync("google.charts.load", "current", new { packages = new[] { "corechart" } });
        // 传入Blazor数据给JS函数
        await JS.InvokeVoidAsync("drawChartWithData", _chartData);
    }
}
  1. JS端处理数据并绘制:
function drawChartWithData(blazorData) {
    // 转换为Google Charts需要的二维数组格式
    const dataArray = [['Activity', 'Hours']];
    blazorData.forEach(item => dataArray.push([item.Name, item.Value]));
    
    const data = google.visualization.arrayToDataTable(dataArray);
    const options = { title: 'Daily Activities' };
    
    const chart = new google.visualization.PieChart(document.getElementById('chart-container'));
    chart.draw(data, options);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 07:24:57