蓝色天空网mbsky.com · 知识 · 实践 · 创造Web Forms · 本地阅读预览
教程 / .NET / Web Forms

WebPages WebGrid

对比手写 HTML 表格遍历数据库记录与使用 WebGrid 帮助器自动生成带排序和分页表格的完整实现,并说明现代 ASP.NET Core 中的替代方案。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

手写 HTML 表格展示数据库记录

`WebGrid` 是 ASP.NET Web Pages 中最具代表性的数据展示帮助器之一。在引入 `WebGrid` 之前,开发者往往需要手动打开数据库(如 `var db = Database.Open("SmallBakery");`)、执行排序查询(`SELECT * FROM Product ORDER BY Name`),再编写完整的 `<table>`、`<tr>`、`<th>` 表头并在 `@foreach (var row in db.Query(selectQueryString))` 循环中逐列输出 `@row.Id`、`@row.Name`、`@row.Description` 与右对齐的 `@row.Price`。

使用 WebGrid 帮助器自动生成排序与分页表格

相比手写大量重复表格标记,`WebGrid` 提供了声明式的快捷方案:它能够自动依据查询结果集生成完整的 HTML 表格,支持自定义列与格式化选项、内建分页导航,并支持点击表头链接切换升序或降序排列。实际代码仅需三步:查询结果 `var data = db.Query("SELECT * FROM Product ORDER BY Id");`,实例化 `var grid = new WebGrid(data);`,最后在页面的 `<div id="grid">` 内调用 `@grid.GetHtml()` 即可完成输出。需补充:ASP.NET Core 已不再内置 `WebGrid` 类,现代开发通常结合 Entity Framework Core 分页查询(`Skip`/`Take`)与 Razor Partial/View Component、Blazor `QuickGrid` 或前端表格组件(如 DataTables)实现同样功能,且排序列名务必做白名单校验以防 SQL 注入。

离线校验 SmallBakery SQLite 手写表格与 WebGrid 排序、分页 HTML 生成

python · 阅读源码
"""Offline ASP.NET semantic verification lab for Chapter 12 (webpages-webgrid)."""
import html
import json
import math
import sqlite3

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


def build_small_bakery_db():
    conn = sqlite3.connect(":memory:")
    conn.row_factory = sqlite3.Row
    conn.execute("CREATE TABLE Product (Id INTEGER PRIMARY KEY, Name TEXT, Description TEXT, Price REAL)")
    conn.executemany(
        "INSERT INTO Product (Id, Name, Description, Price) VALUES (?, ?, ?, ?)",
        [
            (1, "Bread", "Baked fresh every day", 2.99),
            (2, "Strawberry Shortcake", "A delicious treat", 9.99),
            (3, "Apple Pie", "Classic cinnamon crust", 6.50),
            (4, "Chocolate Muffin", "Rich dark cocoa", 3.25),
            (5, "Croissant", "Flaky butter pastry", 2.50),
        ],
    )
    conn.commit()
    return conn


def render_webgrid_html(rows, columns, sort_col=None, sort_dir="ASC", page=1, rows_per_page=3):
    data = [dict(r) for r in rows]
    if sort_col in columns:
        data.sort(key=lambda r: r[sort_col], reverse=(sort_dir.upper() == "DESC"))
    total_pages = max(1, math.ceil(len(data) / rows_per_page))
    page = max(1, min(page, total_pages))
    slice_rows = data[(page - 1) * rows_per_page : page * rows_per_page]
    next_dir = "DESC" if sort_dir.upper() == "ASC" else "ASC"

    ths = "".join(
        f'<th scope="col"><a href="?sort={c}&amp;sortdir={next_dir if c == sort_col else "ASC"}">{html.escape(c)}</a></th>'
        for c in columns
    )
    trs = "".join(
        "<tr>" + "".join(f"<td>{html.escape(str(r[c]))}</td>" for c in columns) + "</tr>"
        for r in slice_rows
    )
    pager = " ".join(f'<a href="?page={p}">{p}</a>' if p != page else f"<span>{p}</span>" for p in range(1, total_pages + 1))
    table_html = f"<table><thead><tr>{ths}</tr></thead><tfoot><tr><td colspan=\"{len(columns)}\">{pager}</td></tr></tfoot><tbody>{trs}</tbody></table>"
    return {"html": table_html, "page": page, "total_pages": total_pages, "row_names": [r["Name"] for r in slice_rows]}


def case_manual_html_table_query():
    conn = build_small_bakery_db()
    rows = conn.execute("SELECT Id, Name, Description, Price FROM Product ORDER BY Name").fetchall()
    body_rows = "".join(
        f'<tr><td>{r["Id"]}</td><td>{html.escape(r["Name"])}</td><td>{html.escape(r["Description"])}</td><td align="right">{r["Price"]:.2f}</td></tr>'
        for r in rows
    )
    expected = {
        "row_count": 5,
        "ordered_names": ["Apple Pie", "Bread", "Chocolate Muffin", "Croissant", "Strawberry Shortcake"],
        "has_right_aligned_price": True,
    }
    actual = {
        "row_count": len(rows),
        "ordered_names": [r["Name"] for r in rows],
        "has_right_aligned_price": '<td align="right">6.50</td>' in body_rows,
    }
    return {
        "name": "manual_html_table_query",
        "summary": "使用内存 SQLite SmallBakery 复现手写 <table> 与 foreach 按 Name 排序渲染商品表",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_webgrid_gethtml_default_order():
    conn = build_small_bakery_db()
    rows = conn.execute("SELECT Id, Name, Description, Price FROM Product ORDER BY Id").fetchall()
    res = render_webgrid_html(rows, ["Id", "Name", "Description", "Price"], page=1, rows_per_page=10)
    expected = {
        "row_names": ["Bread", "Strawberry Shortcake", "Apple Pie", "Chocolate Muffin", "Croissant"],
        "has_thead_and_tbody": True,
        "sortable_headers_present": True,
    }
    actual = {
        "row_names": res["row_names"],
        "has_thead_and_tbody": "<thead>" in res["html"] and "<tbody>" in res["html"],
        "sortable_headers_present": "?sort=Price&amp;sortdir=ASC" in res["html"],
    }
    return {
        "name": "webgrid_gethtml_default_order",
        "summary": "模拟 new WebGrid(data).GetHtml() 自动生成带表头排序链接的 HTML 表格",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_webgrid_sorting_by_price_desc():
    conn = build_small_bakery_db()
    rows = conn.execute("SELECT Id, Name, Description, Price FROM Product ORDER BY Id").fetchall()
    res = render_webgrid_html(rows, ["Id", "Name", "Description", "Price"], sort_col="Price", sort_dir="DESC", page=1, rows_per_page=3)
    expected = {
        "top3_names": ["Strawberry Shortcake", "Apple Pie", "Chocolate Muffin"],
        "toggle_next_sort_asc": True,
    }
    actual = {
        "top3_names": res["row_names"],
        "toggle_next_sort_asc": "?sort=Price&amp;sortdir=ASC" in res["html"],
    }
    return {
        "name": "webgrid_sorting_by_price_desc",
        "summary": "验证 WebGrid 点击列标题按 Price 降序排列并自动切换下一次排序方向为 ASC",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_webgrid_pagination_bounds():
    conn = build_small_bakery_db()
    rows = conn.execute("SELECT Id, Name, Description, Price FROM Product ORDER BY Id").fetchall()
    p1 = render_webgrid_html(rows, ["Id", "Name", "Price"], page=1, rows_per_page=2)
    p3 = render_webgrid_html(rows, ["Id", "Name", "Price"], page=3, rows_per_page=2)
    expected = {
        "total_pages": 3,
        "page1_names": ["Bread", "Strawberry Shortcake"],
        "page3_names": ["Croissant"],
        "pager_has_page2_link": True,
    }
    actual = {
        "total_pages": p1["total_pages"],
        "page1_names": p1["row_names"],
        "page3_names": p3["row_names"],
        "pager_has_page2_link": '<a href="?page=2">2</a>' in p1["html"],
    }
    return {
        "name": "webgrid_pagination_bounds",
        "summary": "验证 WebGrid 分页切片计算、末页余数行展示与页脚分页链接生成",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_manual_html_table_query(),
        case_webgrid_gethtml_default_order(),
        case_webgrid_sorting_by_price_desc(),
        case_webgrid_pagination_bounds(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 离线验证器在内存 SQLite 中复现 SmallBakery Product 表,校验手写 foreach 表格、WebGrid 默认渲染、按 Price 降序切换排序方向及多页分页切片全部通过。
离线校验 SmallBakery SQLite 手写表格与 WebGrid 排序、分页 HTML 生成

所需环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。

当前源码 SHA256:9309a19c846e05cdc5020229dab075ebc7e48c60e3e9c84cb4496f770151742b

下载本站示例源码

本地运行

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

下载WebPages WebGrid实验

所需环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebPages / Razor 语义验证器(本机未启动 IIS / IIS Express / WebMatrix 宿主环境)。

ZIP SHA256:020c3d72091cb4bb3a39637f59d933dcb972e74e161cfa6d10c1b69ae615c3a8

常见错误与边界

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

练习与解答

将手写 `foreach` 表格迁移为 `new WebGrid(data)` + `@grid.GetHtml()` 后,最直接省去了哪些重复开发工作?

展开参考解答

省去了手写 `<thead>`/`<tbody>` 列循环模板、表头排序查询参数(`sort`/`sortdir`)翻转逻辑以及分页偏移计算与页码链接渲染代码。

规范与官方依据