WebForms Button
讲解 ASP.NET WebForms Button 服务器控件的提交按钮与命令按钮两种模式、OnClick/OnCommand 事件路由、CausesValidation 验证控制及现代演进。
学完这一章,你能够
- 讲解 ASP.NET WebForms Button 服务器控件的提交按钮与命令按钮两种模式、OnClick/OnCommand 事件路由、CausesValidation 验证控制及现代演进。
Button 控件的两种角色:提交按钮与命令按钮
`<asp:Button>` 控件用于在网页中渲染一个可点击的下压按钮(默认生成 `<input type="submit">`),其完整属性可查阅 WebForms 控件参考手册。按用途划分,Button 控件可分为提交按钮(Submit Button)和命令按钮(Command Button)两种模式,默认为提交按钮:提交按钮不设置 `CommandName`,点击时将页面回传给服务器并触发绑定到 `OnClick` 的事件处理器;命令按钮则通过设置 `CommandName`(及可选的 `CommandArgument`)赋予按钮具体命令标识,使页面上多个按钮可以共用同一个 `OnCommand` 事件处理器并根据命令名执行不同操作。最简按钮只需在 `<form runat="server">` 中声明 `<asp:Button id="b1" Text="Submit" runat="server" />`。
为按钮绑定服务器端脚本与表单提交
在典型的表单提交场景中,页面声明一个 `TextBox`(`txt1`)、一个绑定 `OnClick="submit"` 的 `Button` 和一个 `Label`(`lbl1`)。用户填写姓名并点击提交按钮后,服务器执行 `submit(sender, e)` 子例程,把 `"Your name is " & txt1.Text` 写入 `lbl1.Text` 返回给浏览器。本站离线实验核对了默认提交按钮渲染、表单提交写入 Label、多命令按钮按 `CommandName`/`CommandArgument` 分发以及 `CausesValidation=True/False` 对非法输入的拦截差异。在现代 ASP.NET Core Razor Pages 中,多按钮分流可通过 `<button type="submit" asp-page-handler="Sort">` 实现,无需依赖 WebForms 整页回传模型。
离线校验 Button 提交模式、命令按钮路由、OnClick 表单更新与 CausesValidation 控制
"""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()
- 核对默认提交按钮渲染、submit 事件更新 Label、Sort/Delete 命令按钮参数分发以及 CausesValidation 阻止或跳过验证分支。
所需环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。
当前源码 SHA256:1b3ecc356089364b9f8757f85ca5efeaa924e8255339acde86ee69a47cb429c5
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 ASP.NET WebForms 语义验证器(本机未启动 IIS / ASP.NET WebForms 运行时宿主)。
ZIP SHA256:cf1980e555d79ace038ffa0ebd6b43660f0bfeacf0961db2188605fadd793fa1
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 WebForms 中,提交按钮(Submit Button)与命令按钮(Command Button)的核心区别是什么?
展开参考解答
提交按钮没有 `CommandName`,主要通过各自的 `OnClick` 事件处理器响应;命令按钮设置了 `CommandName`(并可附带 `CommandArgument`),允许多个按钮共享同一个 `OnCommand` 处理器按命令名称分流执行。