蓝色天空.知识 · 实践 · 创造
我的收藏
Web Forms 教程目录 55章
Web Forms / LEARN BY DOING

WebPages 图表

讲解 ASP.NET Web Pages Chart 帮助器从数组、数据库查询(DataBindTable 与 AddSeries 两种方式)及 XML 文件生成柱形图与饼图的完整用法,并标注现代前后端分离图表替代方案。

学完这一章,你能够

  • 讲解 ASP.NET Web Pages Chart 帮助器从数组、数据库查询(DataBindTable 与 AddSeries 两种方式)及 XML 文件生成柱形图与饼图的完整用法,并标注现代前后端分离图表替代方案。

Chart 帮助器能力与支持的数据来源

继 `WebGrid` 表格展示之后,`Chart` 帮助器提供了在网页中以图形化形式可视化数据的能力。它能够渲染面积图、条形图、柱形图、折线图、饼图等标准统计图表,也支持股票图等专业图表,并允许定制多种配色主题与标签格式(原页此处附有两张图表样式示例图,未入本地缓存,已在待办项登记)。图表所需数据可以来自内存数组、数据库查询结果或外部 XML 等数据文件。

根据数组创建柱形图

最简场景是直接传入两个字符串数组绘制员工柱形图:调用 `new Chart(width: 600, height: 400)` 创建指定宽高的图表实例;通过 `.AddTitle("Employees")` 设置图表标题;通过 `.AddSeries(...)` 添加数据系列,其中 `chartType: "column"` 指定柱形图类型,`xValue` 传入 X 轴分类名称数组(`Peter`、`Andrew`、`Julie`、`Mary`、`Dave`),`yValues` 传入对应的 Y 轴数值数组(`2`、`6`、`4`、`5`、`3`);最后调用 `.Write()` 将图表图像直接输出到 HTTP 响应流。

根据数据库查询与 XML 数据创建图表

结合数据库绘制图表时,先用 `var db = Database.Open("SmallBakery");` 打开数据库并执行 `var dbdata = db.Query("SELECT Name, Price FROM Product");` 获取结果集,再创建 `Chart` 实例并设置标题 `"Product Sales"`。绑定结果集有两种常见方式:其一调用 `.DataBindTable(dataSource: dbdata, xField: "Name")`,写法最省事,会自动将其余数值列绑定为数据系列;其二调用 `.AddSeries(chartType: "Pie", xValue: dbdata, xField: "Name", yValues: dbdata, yFields: "Price")`,虽然多写几个命名参数,但能精确控制图表类型(如饼图)与字段映射,更加灵活。

第三种数据来源是 XML 文件:先引入 `@using System.Data;`,实例化 `DataSet`,依次调用 `ReadXmlSchema(Server.MapPath("data.xsd"))` 与 `ReadXml(Server.MapPath("data.xml"))` 加载架构与数据,再通过 `new DataView(dataSet.Tables[0])` 包装为视图,并将其传给 `AddSeries("Default", chartType: "Pie", xValue: dataView, xField: "Name", yValues: dataView, yFields: "Sales")` 后调用 `.Write()` 输出(注意原代码片段末尾多写了一个多余的右花括号 `}`,实际编码时应删去以保证 Razor 块闭合匹配)。需补充的是,`System.Web.Helpers.Chart` 底层依赖 Windows GDI+,在现代跨平台 ASP.NET Core 中已不再提供;推荐后端接口返回 JSON 统计数据并由前端 Chart.js / ECharts 渲染,或在服务端使用 SkiaSharp / ScottPlot / SVG 模板生成矢量图。

离线校验数组柱形图、SQLite DataBindTable、AddSeries 饼图与 XML 数据集图表构建

含完整源码 · 200 行
展开查看收起
python
"""Offline ASP.NET semantic verification lab for Chapter 13 (webpages-chart)."""
import json
import sqlite3
import xml.etree.ElementTree as ET

VERSION = "CPython 3.12.14 offline ASP.NET WebPages/Core semantic verifier (IIS/WebMatrix absent)"


class OfflineChartBuilder:
    def __init__(self, width: int, height: int):
        self.width = width
        self.height = height
        self.title = ""
        self.series = []

    def add_title(self, title: str):
        self.title = title
        return self

    def add_series(self, name="Default", chart_type="column", x_values=None, y_values=None):
        self.series.append({
            "name": name,
            "chart_type": chart_type,
            "points": list(zip(x_values or [], [float(y) for y in (y_values or [])])),
        })
        return self

    def data_bind_table(self, rows, x_field: str):
        x_vals = [r[x_field] for r in rows]
        y_fields = [k for k in rows[0].keys() if k != x_field]
        for yf in y_fields:
            self.add_series(name=yf, chart_type="column", x_values=x_vals, y_values=[r[yf] for r in rows])
        return self

    def write_svg(self) -> str:
        s0 = self.series[0]
        bars = []
        if s0["chart_type"].lower() == "pie":
            total = sum(v for _, v in s0["points"]) or 1.0
            slices = [f'<g data-label="{k}" data-share="{round(v / total * 100, 1)}%"></g>' for k, v in s0["points"]]
            body = "".join(slices)
        else:
            max_v = max((v for _, v in s0["points"]), default=1.0)
            for idx, (k, v) in enumerate(s0["points"]):
                h = round(v / max_v * (self.height - 80), 1)
                bars.append(f'<rect data-x="{k}" data-y="{v}" x="{40 + idx * 90}" height="{h}" width="50" />')
            body = "".join(bars)
        return f'<svg width="{self.width}" height="{self.height}"><title>{self.title}</title>{body}</svg>'


def case_chart_from_array_column():
    chart = (
        OfflineChartBuilder(600, 400)
        .add_title("Employees")
        .add_series(
            chart_type="column",
            x_values=["Peter", "Andrew", "Julie", "Mary", "Dave"],
            y_values=["2", "6", "4", "5", "3"],
        )
    )
    svg = chart.write_svg()
    expected = {
        "dimensions": [600, 400],
        "title": "Employees",
        "chart_type": "column",
        "point_count": 5,
        "max_employee": "Andrew",
        "svg_valid": True,
    }
    pts = chart.series[0]["points"]
    actual = {
        "dimensions": [chart.width, chart.height],
        "title": chart.title,
        "chart_type": chart.series[0]["chart_type"],
        "point_count": len(pts),
        "max_employee": max(pts, key=lambda p: p[1])[0],
        "svg_valid": svg.startswith('<svg width="600" height="400"><title>Employees</title>'),
    }
    return {
        "name": "chart_from_array_column",
        "summary": "模拟根据字符串数组调用 Chart.AddTitle 与 AddSeries(chartType: 'column') 构建柱形图并输出 SVG",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_chart_from_db_databindtable():
    conn = sqlite3.connect(":memory:")
    conn.execute("CREATE TABLE Product (Name TEXT, Price REAL)")
    conn.executemany(
        "INSERT INTO Product VALUES (?, ?)",
        [("Bread", 2.99), ("Shortcake", 9.99), ("Apple Pie", 6.50)],
    )
    rows = [{"Name": r[0], "Price": r[1]} for r in conn.execute("SELECT Name, Price FROM Product")]
    chart = OfflineChartBuilder(600, 400).add_title("Product Sales").data_bind_table(rows, x_field="Name")
    svg = chart.write_svg()
    expected = {
        "title": "Product Sales",
        "series_name": "Price",
        "x_labels": ["Bread", "Shortcake", "Apple Pie"],
        "svg_contains_shortcake": True,
    }
    actual = {
        "title": chart.title,
        "series_name": chart.series[0]["name"],
        "x_labels": [p[0] for p in chart.series[0]["points"]],
        "svg_contains_shortcake": 'data-x="Shortcake"' in svg,
    }
    return {
        "name": "chart_from_db_databindtable",
        "summary": "模拟数据库查询并通过 DataBindTable(dataSource, xField: 'Name') 自动绑定系列构建图表",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_chart_from_db_addseries_pie():
    rows = [("Bread", 2.0), ("Shortcake", 5.0), ("Apple Pie", 3.0)]
    chart = (
        OfflineChartBuilder(600, 400)
        .add_title("Product Sales")
        .add_series(
            chart_type="Pie",
            x_values=[r[0] for r in rows],
            y_values=[r[1] for r in rows],
        )
    )
    svg = chart.write_svg()
    expected = {
        "chart_type": "Pie",
        "shares_sum_100": True,
        "shortcake_50pct": True,
    }
    actual = {
        "chart_type": chart.series[0]["chart_type"],
        "shares_sum_100": sum(v for _, v in chart.series[0]["points"]) == 10.0,
        "shortcake_50pct": 'data-label="Shortcake" data-share="50.0%"' in svg,
    }
    return {
        "name": "chart_from_db_addseries_pie",
        "summary": "模拟数据库结果通过 AddSeries(chartType: 'Pie', xField, yFields) 显式指定饼图与占比",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_chart_from_xml_dataset():
    xml_doc = """
    <Employees>
      <Employee><Name>Peter</Name><Sales>20</Sales></Employee>
      <Employee><Name>Mary</Name><Sales>50</Sales></Employee>
      <Employee><Name>Dave</Name><Sales>30</Sales></Employee>
    </Employees>
    """
    root = ET.fromstring(xml_doc)
    names = [el.findtext("Name") for el in root.findall("Employee")]
    sales = [float(el.findtext("Sales")) for el in root.findall("Employee")]
    chart = (
        OfflineChartBuilder(600, 400)
        .add_title("Sales Per Employee")
        .add_series(name="Default", chart_type="Pie", x_values=names, y_values=sales)
    )
    svg = chart.write_svg()
    expected = {
        "title": "Sales Per Employee",
        "series_name": "Default",
        "names": ["Peter", "Mary", "Dave"],
        "mary_50pct": True,
    }
    actual = {
        "title": chart.title,
        "series_name": chart.series[0]["name"],
        "names": [p[0] for p in chart.series[0]["points"]],
        "mary_50pct": 'data-label="Mary" data-share="50.0%"' in svg,
    }
    return {
        "name": "chart_from_xml_dataset",
        "summary": "模拟解析 XML 数据源并绑定 Default 饼图系列输出 Sales Per Employee 图表",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_chart_from_array_column(),
        case_chart_from_db_databindtable(),
        case_chart_from_db_addseries_pie(),
        case_chart_from_xml_dataset(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
离线验证器确认 600×400 数组柱形图、SQLite DataBindTable 自动系列、数据库饼图占比计算以及 XML DataSet 饼图 SVG 全部确定性生成通过。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a3001.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Web Forms

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3001.zip

下载课程关联工程包:Web Forms

课程关联工程包(登记关联55章) · 含当前章节或实例 · mbskycom202612a2981.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

`DataBindTable()` 写法更简洁,适合快速把查询表中的列自动绑定为默认柱形图;`AddSeries()` 则允许显式指定 `chartType`(如 `Pie`)、系列名以及精确的 `xField`/`yFields` 映射,灵活性更高。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习