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

WebForms Repeater

详解 ASP.NET WebForms Repeater 模板化数据控件:绑定 cdcatalog.xml、组合 HeaderTemplate/ItemTemplate/FooterTemplate、使用 AlternatingItemTemplate 与 SeparatorTemplate 以及现代 Razor/Blazor 对应写法。

学完这一章,你能够

  • 详解 ASP.NET WebForms Repeater 模板化数据控件:绑定 cdcatalog.xml、组合 HeaderTemplate/ItemTemplate/FooterTemplate、使用 AlternatingItemTemplate 与 SeparatorTemplate 以及现代 Razor/Blazor 对应写法。

准备唱片目录 XML 并绑定 DataSet 到 Repeater

`<asp:Repeater>` 控件用于按开发者完全自定义的 HTML 模板重复渲染被绑定数据源中的每一条记录,可灵活绑定数据库表、XML 文件或内存集合。与自带布局外壳的控件不同,`Repeater` 本身不输出任何多余 HTML 标签,赋予前端结构极高自由度。本章示例以 `cdcatalog.xml` 为数据源,根节点 `<catalog>` 包含 5 张 `<cd>` 唱片记录,每条记录具备 `title`、`artist`、`country`、`company`、`price` 和 `year` 六个字段。

绑定流程分为四步:首先在页面顶部添加 `<%@ Import Namespace="System.Data" %>`;其次在 `Page_Load` 的首次加载判断中创建 `DataSet` 并调用 `mycdcatalog.ReadXml(MapPath("cdcatalog.xml"))` 加载数据,再赋值给 `cdcatalog.DataSource` 并调用 `cdcatalog.DataBind()`;接着在表单内声明 `<asp:Repeater id="cdcatalog" runat="server">`,内部按需定义三段基础模板——`<HeaderTemplate>` 最先渲染且仅出现一次(常放 `<table>` 起始标签与表头行 `<th>`),`<ItemTemplate>` 会为 `DataSet` 中的每一条记录重复渲染一次,`<FooterTemplate>` 最后渲染且仅出现一次(常放闭合标签 `</table>`);最后在 `<ItemTemplate>` 的单元格中使用数据绑定表达式 `<%#Container.DataItem("fieldname")%>` 输出对应字段值(生产实践建议配合 `Server.HtmlEncode` 或 `<%: ... %>` 防止 XSS)。

使用 AlternatingItemTemplate 实现隔行变色

若想为长表格增加斑马纹视觉层次,只需在 `<ItemTemplate>` 之后追加 `<AlternatingItemTemplate>` 元素。渲染时,偶数索引项(第 1、3、5 行)采用 `<ItemTemplate>`,奇数索引项(第 2、4 行)则自动切换为 `<AlternatingItemTemplate>`(示例中为 `<tr bgcolor="#e8e8e8">`,现代页面推荐使用 CSS 类与 `:nth-child(even)`)。离线实验验证了 5 条 CD 记录中第 2 条(Bonnie Tyler)与第 4 条(Gary Moore)精确应用了浅灰背景。

使用 SeparatorTemplate 插入记录分隔符与现代演进

`<SeparatorTemplate>` 用于定义每两条相邻记录之间的分隔结构——例如在无边框表格中插入一行横跨 6 列的水平线 `<tr><td colspan="6"><hr /></td></tr>`。需要留意其边界行为:`SeparatorTemplate` 仅出现在相邻两条数据项**之间**,不会出现在第一条之前或最后一条之后,因此 5 条唱片记录恰好输出 4 条分隔线(已由本站离线模板引擎精确验证)。在现代 ASP.NET Core Razor Pages/MVC 与 Blazor 中,`Repeater` 的模板循环已被原生 `@foreach (var cd in Model.Catalog)` 语句取代,代码更简洁且天然支持自动 HTML 编码。

离线实现 WebForms Repeater 模板引擎并验证交替行与分隔行渲染规则

含完整源码 · 211 行
展开查看收起
python
"""Offline ASP.NET WebForms verifier for Chapter 50 (repeater)."""
from __future__ import annotations

import html
import json
import re
import xml.etree.ElementTree as ET

VERSION = "CPython 3.12.14 offline ASP.NET WebForms verifier (IIS/ASP.NET runtime absent)"

CDCATALOG_XML = """<?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1988</year>
  </cd>
  <cd>
    <title>Greatest Hits</title>
    <artist>Dolly Parton</artist>
    <country>USA</country>
    <company>RCA</company>
    <price>9.90</price>
    <year>1982</year>
  </cd>
  <cd>
    <title>Still got the blues</title>
    <artist>Gary Moore</artist>
    <country>UK</country>
    <company>Virgin records</company>
    <price>10.20</price>
    <year>1990</year>
  </cd>
  <cd>
    <title>Eros</title>
    <artist>Eros Ramazzotti</artist>
    <country>EU</country>
    <company>BMG</company>
    <price>9.90</price>
    <year>1997</year>
  </cd>
</catalog>
"""

BIND_RE = re.compile(r'<%#\s*Container\.DataItem\("([^"]+)"\)\s*%>')


def load_cd_catalog(xml_text: str) -> list[dict[str, str]]:
    root = ET.fromstring(xml_text)
    return [
        {child.tag: (child.text or "").strip() for child in cd}
        for cd in root.findall("cd")
    ]


def bind_template(template: str, row: dict[str, str]) -> str:
    return BIND_RE.sub(lambda m: html.escape(row[m.group(1)]), template)


def render_repeater(
    rows: list[dict[str, str]],
    *,
    header: str,
    item: str,
    footer: str,
    alternating_item: str | None = None,
    separator: str | None = None,
) -> str:
    parts = [header]
    for idx, row in enumerate(rows):
        if idx > 0 and separator is not None:
            parts.append(separator)
        tpl = alternating_item if (alternating_item is not None and idx % 2 == 1) else item
        parts.append(bind_template(tpl, row))
    parts.append(footer)
    return "".join(parts)


def main() -> None:
    rows = load_cd_catalog(CDCATALOG_XML)
    header_tpl = (
        '<table border="1" width="100%">'
        "<tr><th>Title</th><th>Artist</th><th>Country</th><th>Company</th><th>Price</th><th>Year</th></tr>"
    )
    item_tpl = (
        "<tr>"
        '<td><%#Container.DataItem("title")%></td>'
        '<td><%#Container.DataItem("artist")%></td>'
        '<td><%#Container.DataItem("country")%></td>'
        '<td><%#Container.DataItem("company")%></td>'
        '<td><%#Container.DataItem("price")%></td>'
        '<td><%#Container.DataItem("year")%></td>'
        "</tr>"
    )
    alt_tpl = item_tpl.replace("<tr>", '<tr bgcolor="#e8e8e8">', 1)
    sep_tpl = '<tr><td colspan="6"><hr /></td></tr>'
    footer_tpl = "</table>"

    basic_html = render_repeater(rows, header=header_tpl, item=item_tpl, footer=footer_tpl)
    alt_html = render_repeater(
        rows, header=header_tpl, item=item_tpl, alternating_item=alt_tpl, footer=footer_tpl
    )
    sep_html = render_repeater(
        rows,
        header=header_tpl.replace('border="1"', 'border="0"'),
        item=item_tpl,
        separator=sep_tpl,
        footer=footer_tpl,
    )

    cases = [
        {
            "name": "parse_cdcatalog_xml_dataset",
            "summary": "解析 cdcatalog.xml 获取 5 张唱片记录与 6 个标准字段",
            "expected": {
                "count": 5,
                "fields": ["title", "artist", "country", "company", "price", "year"],
                "first_title": "Empire Burlesque",
                "last_artist": "Eros Ramazzotti",
            },
            "actual": {
                "count": len(rows),
                "fields": list(rows[0].keys()),
                "first_title": rows[0]["title"],
                "last_artist": rows[-1]["artist"],
            },
            "passed": (
                len(rows) == 5
                and list(rows[0].keys()) == ["title", "artist", "country", "company", "price", "year"]
                and rows[0]["title"] == "Empire Burlesque"
                and rows[-1]["artist"] == "Eros Ramazzotti"
            ),
        },
        {
            "name": "repeater_basic_table_render",
            "summary": "验证 Repeater 的 HeaderTemplate(1次)、ItemTemplate(5次) 与 FooterTemplate(1次) 完整渲染",
            "expected": {
                "table_open_count": 1,
                "table_close_count": 1,
                "tr_count": 6,
                "contains_dylan": True,
                "has_unrendered_binding": False,
            },
            "actual": {
                "table_open_count": basic_html.count("<table "),
                "table_close_count": basic_html.count("</table>"),
                "tr_count": basic_html.count("<tr>"),
                "contains_dylan": "<td>Bob Dylan</td>" in basic_html,
                "has_unrendered_binding": "<%#" in basic_html,
            },
            "passed": (
                basic_html.count("<table ") == 1
                and basic_html.count("</table>") == 1
                and basic_html.count("<tr>") == 6
                and "<td>Bob Dylan</td>" in basic_html
                and "<%#" not in basic_html
            ),
        },
        {
            "name": "repeater_alternating_item_template",
            "summary": "验证 AlternatingItemTemplate 为第 2、4 条记录(奇数索引)应用浅灰背景 #e8e8e8",
            "expected": {
                "alternating_row_count": 2,
                "bonnie_is_alt": True,
                "gary_is_alt": True,
            },
            "actual": {
                "alternating_row_count": alt_html.count('<tr bgcolor="#e8e8e8">'),
                "bonnie_is_alt": '<tr bgcolor="#e8e8e8"><td>Hide your heart</td>' in alt_html,
                "gary_is_alt": '<tr bgcolor="#e8e8e8"><td>Still got the blues</td>' in alt_html,
            },
            "passed": (
                alt_html.count('<tr bgcolor="#e8e8e8">') == 2
                and '<tr bgcolor="#e8e8e8"><td>Hide your heart</td>' in alt_html
                and '<tr bgcolor="#e8e8e8"><td>Still got the blues</td>' in alt_html
            ),
        },
        {
            "name": "repeater_separator_template",
            "summary": "验证 SeparatorTemplate 在 5 条记录之间恰好插入 4 条水平线分隔行(首前末后不插入)",
            "expected": {
                "separator_count": 4,
                "ends_with_last_row_before_table_close": True,
            },
            "actual": {
                "separator_count": sep_html.count(sep_tpl),
                "ends_with_last_row_before_table_close": sep_html.endswith("<td>1997</td></tr></table>"),
            },
            "passed": (
                sep_html.count(sep_tpl) == 4
                and sep_html.endswith("<td>1997</td></tr></table>")
            ),
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
核对 cdcatalog.xml 5 条记录解析、Header/Item/Footer 表格渲染、AlternatingItemTemplate 为第 2/4 行着色及 SeparatorTemplate 恰好插入 4 条分隔线。

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

本地运行

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

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

本章附件与实例包

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

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

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

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

`HeaderTemplate` 渲染 1 次、`ItemTemplate` 渲染 5 次、`SeparatorTemplate` 渲染 4 次(仅位于相邻记录之间)、`FooterTemplate` 渲染 1 次。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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