蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线校验 Button 提交模式、命令按钮路由、OnClick 表单更新与 CausesValidation 控制

PYTHONWindows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。explore-aspnet-button.py
explore-aspnet-button.py135 行
"""Offline ASP.NET WebForms verifier for Chapter 44 (button)."""
from __future__ import annotations

import html
import json

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


class AspButton:
    """Minimal model of System.Web.UI.WebControls.Button (submit & command modes)."""

    def __init__(
        self,
        ctrl_id: str,
        text: str,
        *,
        command_name: str = "",
        command_argument: str = "",
        causes_validation: bool = True,
    ) -> None:
        self.id = ctrl_id
        self.text = text
        self.command_name = command_name
        self.command_argument = command_argument
        self.causes_validation = causes_validation

    @property
    def button_kind(self) -> str:
        return "command" if self.command_name else "submit"

    def render(self) -> str:
        return (
            f'<input type="submit" name="{html.escape(self.id, quote=True)}" '
            f'value="{html.escape(self.text, quote=True)}" '
            f'id="{html.escape(self.id, quote=True)}" />'
        )


def dispatch_command(btn: AspButton) -> str:
    if btn.command_name == "Sort":
        return f"Sorted records: {btn.command_argument}"
    if btn.command_name == "Delete":
        return f"Deleted record: {btn.command_argument}"
    return f"Unknown command: {btn.command_name}"


def simulate_postback(btn: AspButton, input_valid: bool) -> dict[str, object]:
    if btn.causes_validation and not input_valid:
        return {"validation_checked": True, "handler_executed": False, "status": "blocked_by_validator"}
    return {"validation_checked": btn.causes_validation, "handler_executed": True, "status": "executed"}


def main() -> None:
    b1 = AspButton("b1", "Submit")
    rendered_b1 = b1.render()

    # Case 2: TextBox + Submit Button -> Label
    txt1_value = "Grace"
    lbl1_text = f"Your name is {txt1_value}"

    # Case 3: Command buttons sharing OnCommand handler
    btn_sort = AspButton("btnSort", "Sort Asc", command_name="Sort", command_argument="Asc")
    btn_del = AspButton("btnDelete", "Delete Row", command_name="Delete", command_argument="Row-102")

    # Case 4: CausesValidation True vs False
    submit_blocked = simulate_postback(AspButton("btnSave", "Save", causes_validation=True), input_valid=False)
    cancel_allowed = simulate_postback(AspButton("btnCancel", "Cancel", causes_validation=False), input_valid=False)

    cases = [
        {
            "name": "basic_submit_button_render",
            "summary": "验证默认 Button 控件无 CommandName 时作为提交按钮并渲染为 <input type='submit'>",
            "expected": {
                "kind": "submit",
                "html": '<input type="submit" name="b1" value="Submit" id="b1" />',
            },
            "actual": {
                "kind": b1.button_kind,
                "html": rendered_b1,
            },
            "passed": (
                b1.button_kind == "submit"
                and rendered_b1 == '<input type="submit" name="b1" value="Submit" id="b1" />'
            ),
        },
        {
            "name": "button_submit_updates_label",
            "summary": "模拟表单点击 Button 触发 OnClick='submit' 并将 TextBox 值写入 Label",
            "expected": "Your name is Grace",
            "actual": lbl1_text,
            "passed": lbl1_text == "Your name is Grace",
        },
        {
            "name": "command_button_routing",
            "summary": "验证多个命令按钮通过 CommandName 与 CommandArgument 路由到统一 OnCommand 处理器",
            "expected": {
                "sort_kind": "command",
                "sort_result": "Sorted records: Asc",
                "delete_result": "Deleted record: Row-102",
            },
            "actual": {
                "sort_kind": btn_sort.button_kind,
                "sort_result": dispatch_command(btn_sort),
                "delete_result": dispatch_command(btn_del),
            },
            "passed": (
                btn_sort.button_kind == "command"
                and dispatch_command(btn_sort) == "Sorted records: Asc"
                and dispatch_command(btn_del) == "Deleted record: Row-102"
            ),
        },
        {
            "name": "button_causes_validation_flag",
            "summary": "验证 CausesValidation 默认开启会拦截非法输入提交,设为 false 时取消按钮可跳过验证",
            "expected": {
                "save_on_invalid": {"validation_checked": True, "handler_executed": False, "status": "blocked_by_validator"},
                "cancel_on_invalid": {"validation_checked": False, "handler_executed": True, "status": "executed"},
            },
            "actual": {
                "save_on_invalid": submit_blocked,
                "cancel_on_invalid": cancel_allowed,
            },
            "passed": (
                submit_blocked["handler_executed"] is False
                and cancel_allowed["handler_executed"] is True
            ),
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。

入口文件:projects/web-pages-aspnet-button-lab/explore-aspnet-button.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-aspnet-button.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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