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

离线校验 HTML/Web/Validation 三类服务器控件渲染与 RangeValidator 边界规则

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

import html
import json

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


class HtmlAnchorControl:
    """Minimal model of System.Web.UI.HtmlControls.HtmlAnchor."""

    def __init__(self, ctrl_id: str, inner_text: str, href: str = "") -> None:
        self.id = ctrl_id
        self.inner_text = inner_text
        self.href = href

    def render(self) -> str:
        return (
            f'<a id="{html.escape(self.id, quote=True)}" '
            f'href="{html.escape(self.href, quote=True)}">'
            f"{html.escape(self.inner_text)}</a>"
        )


class WebButtonControl:
    """Minimal model of System.Web.UI.WebControls.Button."""

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

    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)}" />'
        )


class RangeValidatorControl:
    """Minimal model of System.Web.UI.WebControls.RangeValidator (Integer mode)."""

    def __init__(self, target_id: str, min_val: int, max_val: int, error_text: str) -> None:
        self.control_to_validate = target_id
        self.minimum_value = min_val
        self.maximum_value = max_val
        self.text = error_text

    def validate(self, raw_value: str) -> tuple[bool, str]:
        if raw_value == "":
            return True, ""
        try:
            num = int(raw_value)
        except ValueError:
            return False, self.text
        if self.minimum_value <= num <= self.maximum_value:
            return True, ""
        return False, self.text


def main() -> None:
    # Case 1: Classic ASP inline spaghetti vs control separation
    spaghetti_positions = ["inline_in_p_tag"]
    control_separation = {"code_location": "script_runat_server_block", "markup_location": "form_runat_server"}

    # Case 2: HtmlAnchor inside <form runat="server">
    link1 = HtmlAnchorControl("link1", "Visit BlueSky!")
    # Simulate Page_Load handler
    link1.href = "https://mbsky.com/?ref=demo&mode=1"
    rendered_anchor = link1.render()
    expected_anchor = '<a id="link1" href="https://mbsky.com/?ref=demo&amp;mode=1">Visit BlueSky!</a>'

    # Case 3: Web Button OnClick handler
    btn = WebButtonControl("button1", "Click me!")
    before_click = btn.render()
    # Simulate submit(Source, e)
    btn.text = "You clicked me!"
    after_click = btn.render()

    # Case 4: RangeValidator + CausesValidation behavior
    validator = RangeValidatorControl("tbox1", 1, 100, "The value must be from 1 to 100!")
    valid_ok, msg_ok = validator.validate("42")
    valid_high, msg_high = validator.validate("150")
    valid_alpha, msg_alpha = validator.validate("abc")
    cancel_btn = WebButtonControl("btnCancel", "Cancel", causes_validation=False)
    skip_validation_ran = cancel_btn.causes_validation

    cases = [
        {
            "name": "classic_asp_spaghetti_limitation",
            "summary": "对比经典 ASP 内联脚本与位置强耦合,核对 ASP.NET 将逻辑移出 HTML 标记的分层结构",
            "expected": {
                "classic_asp_inline_coupled": True,
                "aspnet_code_separated": True,
                "control_categories": ["HTML 服务器控件", "Web 服务器控件", "Validation 服务器控件"],
            },
            "actual": {
                "classic_asp_inline_coupled": spaghetti_positions == ["inline_in_p_tag"],
                "aspnet_code_separated": control_separation["code_location"] != control_separation["markup_location"],
                "control_categories": ["HTML 服务器控件", "Web 服务器控件", "Validation 服务器控件"],
            },
            "passed": True,
        },
        {
            "name": "html_server_control_anchor",
            "summary": "模拟 HtmlAnchor 在 Page_Load 中动态赋值 HRef 并完成 HTML 属性转义",
            "expected": expected_anchor,
            "actual": rendered_anchor,
            "passed": rendered_anchor == expected_anchor,
        },
        {
            "name": "web_server_control_button_click",
            "summary": "验证 <asp:Button> 初始渲染及触发 OnClick 事件处理器后按钮文本变更",
            "expected": {
                "before": '<input type="submit" name="button1" value="Click me!" id="button1" />',
                "after": '<input type="submit" name="button1" value="You clicked me!" id="button1" />',
            },
            "actual": {
                "before": before_click,
                "after": after_click,
            },
            "passed": (
                before_click == '<input type="submit" name="button1" value="Click me!" id="button1" />'
                and after_click == '<input type="submit" name="button1" value="You clicked me!" id="button1" />'
            ),
        },
        {
            "name": "validation_range_validator_control",
            "summary": "验证 RangeValidator 对 1~100 整数边界校验与 CausesValidation=false 跳过校验语义",
            "expected": {
                "valid_42": [True, ""],
                "invalid_150": [False, "The value must be from 1 to 100!"],
                "invalid_abc": [False, "The value must be from 1 to 100!"],
                "cancel_causes_validation": False,
            },
            "actual": {
                "valid_42": [valid_ok, msg_ok],
                "invalid_150": [valid_high, msg_high],
                "invalid_abc": [valid_alpha, msg_alpha],
                "cancel_causes_validation": skip_validation_ran,
            },
            "passed": (
                (valid_ok, msg_ok) == (True, "")
                and (valid_high, msg_high) == (False, "The value must be from 1 to 100!")
                and (valid_alpha, msg_alpha) == (False, "The value must be from 1 to 100!")
                and skip_validation_ran is False
            ),
        },
    ]
    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/aspnet-controls-lab/explore-controls.py

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

下载课程关联工程包:ASP.NET

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

下载课程关联工程包:ASP.NET

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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