蓝色天空网mbsky.com · 知识 · 实践 · 创造Razor · 本地阅读预览
教程 / .NET / Razor

WebForms TextBox

详解 ASP.NET WebForms TextBox 服务器控件的 TextMode、Text、Rows、Columns 属性、按钮提交读取文本及 AutoPostBack + OnTextChanged 自动回传机制。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

TextBox 控件的常用属性与渲染形态

`<asp:TextBox>` 控件用于在页面中创建可供用户输入文本的输入框,其完整属性列表可查阅 WebForms 控件参考手册。根据不同属性配置,同一服务器控件在客户端会渲染为不同形态的 HTML 元素:默认单行模式(`TextMode="SingleLine"`)输出 `<input type="text">`;设置 `TextMode="Password"` 输出密码框 `<input type="password">`(出于安全考虑,回传时默认不将明文密码回写到 HTML `value` 属性);通过 `Text="Hello World!"` 可预置初始文本;设置 `TextMode="MultiLine"` 渲染为 `<textarea>` 多行文本域,并可配合 `Rows="5"` 指定可见行数;设置 `Columns="30"` 则控制单行框的 `size` 或多行框的 `cols` 宽度。

通过按钮提交与 AutoPostBack 响应文本变化

当表单回传至服务器时,服务器端事件代码可以读取或修改 `TextBox` 的 `Text` 内容。最常见的方式是搭配提交按钮:在 `.aspx` 中声明 `txt1`(`TextBox`)、`Button`(绑定 `OnClick="submit"`)以及 `lbl1`(`Label`),当用户点击提交按钮时,服务端执行 `submit(sender, e)` 并将 `"Your name is " & txt1.Text` 写入 `lbl1.Text`。

除点击按钮外,还可以让文本框自身在值改变后自动触发回传:为 `<asp:TextBox>` 同时设置 `OnTextChanged="change"` 与 `AutoPostBack="true"`。当用户修改内容并使文本框失去焦点(在外部点击或按下 Tab 键)时,ASP.NET 生成的客户端 `__doPostBack` 脚本会自动提交表单,服务端比对旧值与新值确认发生变化后执行 `change` 子例程并输出 `"You changed text to " & txt1.Text`。本站离线验证器实测了 6 种属性渲染、提交写入 Label、值变化 vs 未变化的 `TextChanged` 触发条件以及单/多行框的 HTML 转义。在现代 ASP.NET Core 与 Blazor 中,文本框对应标准 `<input asp-for="..." />` / `<textarea>` 或 Blazor `<InputText @bind-Value="..." />`,通常以局部事件或 Fetch 交互替代整页 `AutoPostBack`。

离线校验 TextBox 六种属性渲染、按钮回传读取与 AutoPostBack OnTextChanged 语义

python · 阅读源码
"""Offline ASP.NET WebForms verifier for Chapter 43 (textbox)."""
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_textbox(
    ctrl_id: str,
    *,
    text: str = "",
    text_mode: str = "SingleLine",
    rows: int | None = None,
    columns: int | None = None,
    auto_postback: bool = False,
) -> str:
    mode = text_mode.lower()
    attrs = [f'name="{html.escape(ctrl_id, quote=True)}"', f'id="{html.escape(ctrl_id, quote=True)}"']
    if auto_postback:
        attrs.append(f"onchange=\"__doPostBack('{html.escape(ctrl_id, quote=True)}','')\"")
    if mode == "multiline":
        if rows is not None:
            attrs.append(f'rows="{rows}"')
        if columns is not None:
            attrs.append(f'cols="{columns}"')
        return f"<textarea {' '.join(attrs)}>{html.escape(text)}</textarea>"
    input_type = "password" if mode == "password" else "text"
    attrs.insert(0, f'type="{input_type}"')
    # WebForms Password TextBox does not echo plain-text password value by default
    if mode != "password" and text:
        attrs.append(f'value="{html.escape(text, quote=True)}"')
    if columns is not None:
        attrs.append(f'size="{columns}"')
    return f"<input {' '.join(attrs)} />"


def handle_text_changed(previous_text: str, posted_text: str) -> dict[str, object]:
    changed = previous_text != posted_text
    lbl1 = f"You changed text to {posted_text}" if changed else ""
    return {"event_fired": changed, "lbl1": lbl1}


def main() -> None:
    tb1 = render_textbox("tb1")
    tb2 = render_textbox("tb2", text="secret", text_mode="Password")
    tb4 = render_textbox("tb4", text="Hello World!")
    tb3 = render_textbox("tb3", text_mode="MultiLine")
    tb6 = render_textbox("tb6", text_mode="MultiLine", rows=5)
    tb5 = render_textbox("tb5", columns=30)

    # Case 2: Button submit updates Label
    submitted_name = "Linus"
    submit_lbl = f"Your name is {submitted_name}"

    # Case 3: AutoPostBack + OnTextChanged
    tb_auto = render_textbox("txt1", text="Hello World!", auto_postback=True)
    change_fired = handle_text_changed("Hello World!", "ASP.NET")
    change_unchanged = handle_text_changed("Hello World!", "Hello World!")

    # Case 4: HTML escaping in TextBox and Textarea
    xss_single = render_textbox("tbXss", text='" onclick="alert(1)')
    xss_multi = render_textbox("tbMultiXss", text="</textarea><script>x()</script>", text_mode="MultiLine")

    cases = [
        {
            "name": "textbox_modes_and_dimensions",
            "summary": "验证 TextBox 六种属性组合(默认、Password 不回显明文、预置 Text、MultiLine、Rows=5、Columns=30)",
            "expected": {
                "tb1": '<input type="text" name="tb1" id="tb1" />',
                "tb2": '<input type="password" name="tb2" id="tb2" />',
                "tb4": '<input type="text" name="tb4" id="tb4" value="Hello World!" />',
                "tb3": '<textarea name="tb3" id="tb3"></textarea>',
                "tb6": '<textarea name="tb6" id="tb6" rows="5"></textarea>',
                "tb5": '<input type="text" name="tb5" id="tb5" size="30" />',
            },
            "actual": {
                "tb1": tb1,
                "tb2": tb2,
                "tb4": tb4,
                "tb3": tb3,
                "tb6": tb6,
                "tb5": tb5,
            },
            "passed": (
                tb1 == '<input type="text" name="tb1" id="tb1" />'
                and tb2 == '<input type="password" name="tb2" id="tb2" />'
                and tb4 == '<input type="text" name="tb4" id="tb4" value="Hello World!" />'
                and tb3 == '<textarea name="tb3" id="tb3"></textarea>'
                and tb6 == '<textarea name="tb6" id="tb6" rows="5"></textarea>'
                and tb5 == '<input type="text" name="tb5" id="tb5" size="30" />'
            ),
        },
        {
            "name": "textbox_button_submit_label",
            "summary": "模拟点击 Submit 按钮执行 submit 子例程并将 txt1.Text 拼接写入 lbl1.Text",
            "expected": "Your name is Linus",
            "actual": submit_lbl,
            "passed": submit_lbl == "Your name is Linus",
        },
        {
            "name": "textbox_autopostback_textchanged",
            "summary": "验证 AutoPostBack='true' 生成 __doPostBack 并在文本发生真实变化时触发 OnTextChanged",
            "expected": {
                "has_autopostback_hook": True,
                "when_changed": {"event_fired": True, "lbl1": "You changed text to ASP.NET"},
                "when_same": {"event_fired": False, "lbl1": ""},
            },
            "actual": {
                "has_autopostback_hook": "__doPostBack('txt1','')" in tb_auto,
                "when_changed": change_fired,
                "when_same": change_unchanged,
            },
            "passed": (
                "__doPostBack('txt1','')" in tb_auto
                and change_fired == {"event_fired": True, "lbl1": "You changed text to ASP.NET"}
                and change_unchanged == {"event_fired": False, "lbl1": ""}
            ),
        },
        {
            "name": "textbox_html_encoding_safety",
            "summary": "验证单行与多行 TextBox 渲染用户输入时自动执行 HTML 实体转义",
            "expected": {
                "single_escaped": "&quot; onclick=&quot;alert(1)" in xss_single,
                "multi_escaped": "&lt;/textarea&gt;&lt;script&gt;x()&lt;/script&gt;" in xss_multi,
            },
            "actual": {
                "single_escaped": "&quot; onclick=&quot;alert(1)" in xss_single,
                "multi_escaped": "&lt;/textarea&gt;&lt;script&gt;x()&lt;/script&gt;" in xss_multi,
            },
            "passed": (
                "&quot; onclick=&quot;alert(1)" in xss_single
                and "&lt;/textarea&gt;&lt;script&gt;x()&lt;/script&gt;" in xss_multi
            ),
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 SingleLine/Password/MultiLine/Rows/Columns 渲染输出、提交拼接 Label 文本、AutoPostBack 值变更才触发 OnTextChanged 及 HTML 转义防护。
离线校验 TextBox 六种属性渲染、按钮回传读取与 AutoPostBack OnTextChanged 语义

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

当前源码 SHA256:f275601baa789d830cc169e91af5387b6111333f4465103a9e27164875a1f0af

下载本站示例源码

本地运行

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

下载WebForms TextBox实验

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

ZIP SHA256:f48f7228ee2c32cc93e6059dcede1accc7c73aadadd952d2a262dbba29ff2ce9

常见错误与边界

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

练习与解答

给 `<asp:TextBox>` 设置了 `OnTextChanged="change"`,为什么用户修改文字并移开焦点后事件没有立即触发?

展开参考解答

因为 `AutoPostBack` 默认为 `false`,此时 `TextChanged` 会延后到下一次其他控件触发回传时才在服务端执行;若希望失焦后立即回传,必须显式设置 `AutoPostBack="true"`。

规范与官方依据