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

WebForms 数据绑定

介绍 ASP.NET WebForms 数据绑定(Data Binding)的核心思想、支持绑定的四大列表控件、静态 asp:ListItem 写法与外部数据源解耦优势及现代演进。

学完这一章,你能够

  • 介绍 ASP.NET WebForms 数据绑定(Data Binding)的核心思想、支持绑定的四大列表控件、静态 asp:ListItem 写法与外部数据源解耦优势及现代演进。

支持数据绑定的列表控件与静态选项写法

数据绑定(Data Binding)允许我们将来自数据库、XML 文件或服务器端脚本集合的数据直接填充到带可选项的列表控件中。在 WebForms 中,最常用的四类数据绑定列表控件包括:`asp:RadioButtonList`(单选按钮组)、`asp:CheckBoxList`(复选框组)、`asp:DropDownList`(下拉选择框)以及 `asp:ListBox`(列表框)。在未使用外部数据源时,这些控件的可选项通常需要手工硬编码在一个或多个 `<asp:ListItem value="..." text="..." />` 子标签中(例如静态写入 Norway、Sweden、France、Italy 四个国家选项)。

分离数据与 HTML 及后续数据源路线

采用外部数据源绑定后,选项数据得以从 HTML 标记中彻底分离:当业务需要增删或调整列表条目时,只需更新独立的数据源(内存集合、XML 或数据库),无需改动 `.aspx` 页面结构,极大提升了可维护性。工程实践中还应注意将首次 `DataBind()` 置于 `if Not Page.IsPostBack` 保护内,避免回传时重复绑定冲掉用户当前选中项。接下来的三个章节将依次演示如何从脚本化的集合对象(`ArrayList`、`Hashtable`、`SortedList`)绑定数据。在现代 ASP.NET Core 中,这一思路演进为强类型视图模型配合 `<select asp-items="Model.Countries">` 或 Blazor `@foreach` 声明式渲染。

离线校验静态 ListItem 渲染、四大列表控件绑定形态与外部数据源解耦更新

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

import html
import json

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


def render_list_control(control_type: str, ctrl_id: str, items: list[tuple[str, str]]) -> str:
    """Render WebForms data-bound list controls to minimal representative HTML."""
    ctype = control_type.lower()
    if ctype == "radiobuttonlist":
        rows = "".join(
            f'<tr><td><input id="{ctrl_id}_{i}" type="radio" name="{ctrl_id}" value="{html.escape(val, quote=True)}" />'
            f'<label for="{ctrl_id}_{i}">{html.escape(txt)}</label></td></tr>'
            for i, (val, txt) in enumerate(items)
        )
        return f'<table id="{ctrl_id}">{rows}</table>'
    if ctype == "checkboxlist":
        rows = "".join(
            f'<tr><td><input id="{ctrl_id}_{i}" type="checkbox" name="{ctrl_id}${i}" value="{html.escape(val, quote=True)}" />'
            f'<label for="{ctrl_id}_{i}">{html.escape(txt)}</label></td></tr>'
            for i, (val, txt) in enumerate(items)
        )
        return f'<table id="{ctrl_id}">{rows}</table>'
    if ctype == "dropdownlist":
        opts = "".join(
            f'<option value="{html.escape(val, quote=True)}">{html.escape(txt)}</option>'
            for val, txt in items
        )
        return f'<select name="{ctrl_id}" id="{ctrl_id}">{opts}</select>'
    if ctype == "listbox":
        opts = "".join(
            f'<option value="{html.escape(val, quote=True)}">{html.escape(txt)}</option>'
            for val, txt in items
        )
        return f'<select size="4" name="{ctrl_id}" id="{ctrl_id}">{opts}</select>'
    raise ValueError(f"Unsupported list control: {control_type}")


def main() -> None:
    static_items = [("N", "Norway"), ("S", "Sweden"), ("F", "France"), ("I", "Italy")]
    radio_html = render_list_control("RadioButtonList", "countrylist", static_items)

    # Case 2: All 4 supported list controls bound to the same data source
    controls = ["RadioButtonList", "CheckBoxList", "DropDownList", "ListBox"]
    bound_tags = {
        c: render_list_control(c, "ctrl", static_items[:2])
        for c in controls
    }

    # Case 3: Updating external data source updates rendered options without touching markup
    updated_source = static_items + [("D", "Denmark")]
    updated_dropdown = render_list_control("DropDownList", "countryDrop", updated_source)

    # Case 4: IsPostBack guard preserves selected value vs unguarded rebind resets selection
    def simulate_postback_bind(guard_postback: bool, user_selected: str) -> str:
        selected = user_selected
        if not guard_postback:
            # Re-binding on postback resets selection to first item
            selected = static_items[0][0]
        return selected

    guarded_sel = simulate_postback_bind(guard_postback=True, user_selected="F")
    unguarded_sel = simulate_postback_bind(guard_postback=False, user_selected="F")

    cases = [
        {
            "name": "static_radiobuttonlist_items",
            "summary": "解析静态声明的 asp:RadioButtonList 及 4 个 asp:ListItem 并核对渲染输出",
            "expected": {
                "item_count": 4,
                "contains_norway": True,
                "contains_italy": True,
            },
            "actual": {
                "item_count": radio_html.count('type="radio"'),
                "contains_norway": 'value="N"' in radio_html and ">Norway<" in radio_html,
                "contains_italy": 'value="I"' in radio_html and ">Italy<" in radio_html,
            },
            "passed": (
                radio_html.count('type="radio"') == 4
                and 'value="N"' in radio_html
                and ">Norway<" in radio_html
                and 'value="I"' in radio_html
                and ">Italy<" in radio_html
            ),
        },
        {
            "name": "four_list_controls_binding",
            "summary": "核对 RadioButtonList、CheckBoxList、DropDownList、ListBox 四类列表控件的数据绑定渲染形态",
            "expected": {
                "RadioButtonList": 'type="radio"',
                "CheckBoxList": 'type="checkbox"',
                "DropDownList": "<select name=\"ctrl\"",
                "ListBox": '<select size="4"',
            },
            "actual": {
                "RadioButtonList": 'type="radio"' if 'type="radio"' in bound_tags["RadioButtonList"] else "",
                "CheckBoxList": 'type="checkbox"' if 'type="checkbox"' in bound_tags["CheckBoxList"] else "",
                "DropDownList": '<select name="ctrl"' if '<select name="ctrl"' in bound_tags["DropDownList"] else "",
                "ListBox": '<select size="4"' if '<select size="4"' in bound_tags["ListBox"] else "",
            },
            "passed": (
                'type="radio"' in bound_tags["RadioButtonList"]
                and 'type="checkbox"' in bound_tags["CheckBoxList"]
                and '<select name="ctrl"' in bound_tags["DropDownList"]
                and '<select size="4"' in bound_tags["ListBox"]
            ),
        },
        {
            "name": "datasource_separation_update",
            "summary": "验证数据与 HTML 分离后,在外部数据源追加 Denmark 无需修改页面标记即可同步呈现 5 项",
            "expected": {"option_count": 5, "has_denmark": True},
            "actual": {
                "option_count": updated_dropdown.count("<option "),
                "has_denmark": '<option value="D">Denmark</option>' in updated_dropdown,
            },
            "passed": (
                updated_dropdown.count("<option ") == 5
                and '<option value="D">Denmark</option>' in updated_dropdown
            ),
        },
        {
            "name": "databind_lifecycle_idempotency",
            "summary": "对比首次加载绑定(IsPostBack 保护)保留用户选中项 F 与未保护重绑重置为首项 N 的差异",
            "expected": {"guarded_selected": "F", "unguarded_selected": "N"},
            "actual": {"guarded_selected": guarded_sel, "unguarded_selected": unguarded_sel},
            "passed": guarded_sel == "F" and unguarded_sel == "N",
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
核对静态 4 项 RadioButtonList 渲染、四大列表控件统一数据绑定输出、外部追加选项同步生效及 IsPostBack 保护防止选中态重置。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:Razor

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

下载课程关联工程包:Razor

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

因为每次回传都会重新执行 `Page_Load`,如果不加 `IsPostBack` 保护,重新调用 `DataBind()` 会重建所有 `ListItem` 并重置用户的选中状态,同时还会浪费不必要的数据查询开销。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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