WebForms DataList
详解 ASP.NET WebForms DataList 控件与 Repeater 的核心区别(默认表格外壳)、gridlines 边框、控件级样式属性配置及 AlternatingItemTemplate 交替行样式。
学完这一章,你能够
- 详解 ASP.NET WebForms DataList 控件与 Repeater 的核心区别(默认表格外壳)、gridlines 边框、控件级样式属性配置及 AlternatingItemTemplate 交替行样式。
DataList 与 Repeater 的区别及基础绑定
`<asp:DataList>` 控件与 `Repeater` 类似,同样用于将数据库表、XML 文件或集合中的记录以重复模板形式输出;二者的核心区别在于:`DataList` 会**默认自动用 HTML 表格**(`<table><tr><td>`)包裹表头、每条数据项和页脚,而无需开发者手工编写外层 `<table>` 与 `<tr>` 标记。本章继续采用包含 5 条唱片记录的 `cdcatalog.xml` 演示其用法。
在页面顶部导入 `System.Data` 并在 `Page_Load` 首次加载时用 `DataSet.ReadXml(MapPath("cdcatalog.xml"))` 读取数据绑定到 `cdcatalog` 后,即可在 `<asp:DataList id="cdcatalog" gridlines="both" runat="server">` 中声明 `<HeaderTemplate>`(仅输出一次表头 `My CD Catalog`)、`<ItemTemplate>`(每条记录渲染为 `"Title" of Artist - $Price`)与 `<FooterTemplate>`(仅输出一次版权页脚)。设置 `gridlines="both"` 会在生成的表格上启用横纵网格线边框(渲染为 `rules="all" border="1"`)。
为 DataList 添加控件级样式与交替行模板
`DataList` 内置了丰富的声明式样式属性,可直接写在 `<asp:DataList>` 起始标签上美化输出:包括表格级的 `cellpadding`、`cellspacing`、`borderstyle="inset"`、`backcolor="#e8e8e8"`、`width="100%"`,以及针对不同模板区的 `headerstyle-*`(字体、字号、居中与粗体)、`itemstyle-*`(背景色 `#778899` 与白色前景字 `#ffffff`)和 `footerstyle-*`(小字号斜体)。
同样可以在 `<ItemTemplate>` 后加入 `<AlternatingItemTemplate>`,并搭配 `alternatingitemstyle-backcolor="#e8e8e8"` 与 `alternatingitemstyle-forecolor="#000000"` 为交替行设置独立配色。本站离线验证器完整模拟了 `DataList` 自动表格封装、`gridlines="both"` 属性、各类模板内联样式映射以及 5 条唱片呈现出“3 条深蓝灰底白字 + 2 条浅灰底黑字”的交替效果。在现代 ASP.NET Core / Blazor 实践中,推荐以纯语义化 HTML 结合独立 CSS(如 Flexbox/Grid 与样式表)替代 WebForms 控件上的大量内联表现属性,从而让样式更易维护且符合无障碍规范。
离线校验 DataList 自动表格外壳、gridlines 边框、模板样式属性与交替行配色
"""Offline ASP.NET WebForms verifier for Chapter 51 (datalist)."""
from __future__ import annotations
import html
import json
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><price>10.90</price></cd>
<cd><title>Hide your heart</title><artist>Bonnie Tyler</artist><price>9.90</price></cd>
<cd><title>Greatest Hits</title><artist>Dolly Parton</artist><price>9.90</price></cd>
<cd><title>Still got the blues</title><artist>Gary Moore</artist><price>10.20</price></cd>
<cd><title>Eros</title><artist>Eros Ramazzotti</artist><price>9.90</price></cd>
</catalog>
"""
def load_cds(xml_text: str) -> list[dict[str, str]]:
root = ET.fromstring(xml_text)
return [
{c.tag: (c.text or "").strip() for c in cd}
for cd in root.findall("cd")
]
def render_datalist(
ctrl_id: str,
rows: list[dict[str, str]],
*,
gridlines: str | None = None,
table_attrs: dict[str, str] | None = None,
header_style: str = "",
item_style: str = "",
alt_item_style: str = "",
footer_style: str = "",
header_text: str = "My CD Catalog",
footer_text: str = "Copyright Demo",
) -> str:
"""DataList automatically wraps header, items, and footer inside an HTML <table>."""
attrs = [f'id="{html.escape(ctrl_id, quote=True)}"']
if gridlines == "both":
attrs.extend(['rules="all"', 'border="1"'])
for k, v in (table_attrs or {}).items():
attrs.append(f'{k}="{html.escape(v, quote=True)}"')
def td(content: str, style: str) -> str:
style_attr = f' style="{style}"' if style else ""
return f"<tr><td{style_attr}>{content}</td></tr>"
parts = [f"<table {' '.join(attrs)}>"]
parts.append(td(html.escape(header_text), header_style))
for idx, row in enumerate(rows):
line = f'"{html.escape(row["title"])}" of {html.escape(row["artist"])} - ${html.escape(row["price"])}'
style = alt_item_style if (alt_item_style and idx % 2 == 1) else item_style
parts.append(td(line, style))
parts.append(td(html.escape(footer_text), footer_style))
parts.append("</table>")
return "".join(parts)
def main() -> None:
rows = load_cds(CDCATALOG_XML)
# Case 1: Auto-table wrapping even without user <table> tags
auto_table_html = render_datalist("cdcatalog", rows)
# Case 2: gridlines="both"
grid_html = render_datalist("cdcatalog", rows, gridlines="both")
# Case 3: Styled DataList (headerstyle, itemstyle, footerstyle)
styled_html = render_datalist(
"cdcatalog",
rows,
table_attrs={
"cellpadding": "2",
"cellspacing": "2",
"style": "background-color:#e8e8e8;border-style:inset;width:100%;",
},
header_style="font-family:Verdana;font-size:12pt;text-align:center;font-weight:bold;",
item_style="background-color:#778899;color:#ffffff;",
footer_style="font-size:9pt;font-style:italic;",
)
# Case 4: AlternatingItemTemplate + alternatingitemstyle
alt_html = render_datalist(
"cdcatalog",
rows,
table_attrs={
"cellpadding": "2",
"cellspacing": "2",
"style": "background-color:#e8e8e8;border-style:inset;width:100%;",
},
header_style="font-family:Verdana;font-size:12pt;text-align:center;font-weight:bold;",
item_style="background-color:#778899;color:#ffffff;",
alt_item_style="background-color:#e8e8e8;color:#000000;",
footer_style="font-size:9pt;font-style:italic;",
)
cases = [
{
"name": "datalist_xml_load_and_auto_table",
"summary": "验证 DataList 无需手写 <table> 即自动为表头、5 条数据项与页脚生成 7 行表格布局",
"expected": {"row_count": 5, "has_auto_table": True, "tr_count": 7},
"actual": {
"row_count": len(rows),
"has_auto_table": auto_table_html.startswith('<table id="cdcatalog">'),
"tr_count": auto_table_html.count("<tr>"),
},
"passed": (
len(rows) == 5
and auto_table_html.startswith('<table id="cdcatalog">')
and auto_table_html.count("<tr>") == 7
),
},
{
"name": "datalist_gridlines_basic_render",
"summary": "验证设置 gridlines='both' 后输出 rules='all' border='1' 并正确格式化唱片标题与价格",
"expected": {
"has_grid_border": True,
"first_item_rendered": True,
},
"actual": {
"has_grid_border": 'rules="all" border="1"' in grid_html,
"first_item_rendered": '"Empire Burlesque" of Bob Dylan - $10.90' in grid_html,
},
"passed": (
'rules="all" border="1"' in grid_html
and '"Empire Burlesque" of Bob Dylan - $10.90' in grid_html
),
},
{
"name": "datalist_styled_templates_render",
"summary": "验证 DataList 表格级样式与 headerstyle/itemstyle/footerstyle 属性映射至内联 CSS",
"expected": {
"has_border_inset": True,
"header_styled_count": 1,
"item_styled_count": 5,
"footer_italic_count": 1,
},
"actual": {
"has_border_inset": "border-style:inset" in styled_html,
"header_styled_count": styled_html.count("font-family:Verdana;font-size:12pt"),
"item_styled_count": styled_html.count("background-color:#778899;color:#ffffff;"),
"footer_italic_count": styled_html.count("font-size:9pt;font-style:italic;"),
},
"passed": (
"border-style:inset" in styled_html
and styled_html.count("font-family:Verdana;font-size:12pt") == 1
and styled_html.count("background-color:#778899;color:#ffffff;") == 5
and styled_html.count("font-size:9pt;font-style:italic;") == 1
),
},
{
"name": "datalist_alternating_styled_render",
"summary": "验证加入 AlternatingItemTemplate 后 5 条数据项呈 3 条深蓝灰底白字 + 2 条浅灰底黑字交替展示",
"expected": {"primary_items": 3, "alternating_items": 2},
"actual": {
"primary_items": alt_html.count("background-color:#778899;color:#ffffff;"),
"alternating_items": alt_html.count("background-color:#e8e8e8;color:#000000;"),
},
"passed": (
alt_html.count("background-color:#778899;color:#ffffff;") == 3
and alt_html.count("background-color:#e8e8e8;color:#000000;") == 2
),
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对自动生成 7 行 HTML 表格、gridlines=both 边框输出、headerstyle/itemstyle/footerstyle 样式映射及 3+2 交替配色统计。
所需环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。
当前源码 SHA256:3e26fd4396b55f6bdab4f0de03c59fd69c8aedb675fada69ebe00fa9bf93573d
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。
ZIP SHA256:f2cb3fb649ca6d1b91eb9ad08fe5413615f48df3703b55d4a73591fa039e2b66
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`DataList` 控件与 `Repeater` 控件在输出 HTML 结构上最直接的差别是什么?
展开参考解答
`Repeater` 不自动生成任何外层 HTML 标记,完全依赖开发者在模板中手写 `<table>` 或 `<ul>`;而 `DataList` 默认会自动用 `<table><tr><td>` 包裹表头、每个数据项和页脚,并提供 `gridlines`、`itemstyle-*` 等内置表格样式属性。