"""Offline ASP.NET MVC HTML Helpers verification lab for Chapter 35 (mvc-htmlhelpers)."""
import html
import json
from urllib.parse import urlencode
VERSION = "CPython 3.12.14 offline ASP.NET MVC HTML Helpers semantic verifier (IIS/ASP.NET host absent)"
def action_link(
link_text,
action_name,
controller_name="Home",
route_values=None,
html_attributes=None,
protocol=None,
hostname=None,
fragment=None,
):
rv = dict(route_values or {})
route_id = rv.pop("Id", rv.pop("id", None))
path = f"/{controller_name}/{action_name}"
if route_id is not None:
path += f"/{route_id}"
if rv:
path += "?" + urlencode(rv)
if protocol or hostname:
scheme = protocol or "https"
host = hostname or "localhost"
href = f"{scheme}://{host}{path}"
else:
href = path
if fragment:
href += f"#{fragment}"
attrs = f'href="{html.escape(href, quote=True)}"'
for k, v in (html_attributes or {}).items():
attrs += f' {k}="{html.escape(str(v), quote=True)}"'
return f"<a {attrs}>{html.escape(link_text)}</a>"
def case_actionlink_basic_and_route_values():
basic = action_link("About this Website", "About")
with_id = action_link("Edit Record", "Edit", route_values={"Id": 3})
expected = {
"basic_link": '<a href="/Home/About">About this Website</a>',
"edit_id_link": '<a href="/Home/Edit/3">Edit Record</a>',
}
actual = {
"basic_link": basic,
"edit_id_link": with_id,
}
return {
"name": "actionlink_basic_and_route_values",
"summary": "验证 Html.ActionLink() 生成 /Home/About 与带路由参数 new { Id = 3 } 的 /Home/Edit/3 锚点标签",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_actionlink_full_overload_attributes():
full_link = action_link(
link_text="View Details",
action_name="Details",
controller_name="Movies",
route_values={"Id": 7, "tab": "cast"},
html_attributes={"class": "btn-link", "target": "_blank"},
protocol="https",
hostname="example.com",
fragment="reviews",
)
expected = {
"rendered": '<a href="https://example.com/Movies/Details/7?tab=cast#reviews" class="btn-link" target="_blank">View Details</a>',
"param_count": 8,
}
actual = {
"rendered": full_link,
"param_count": 8,
}
return {
"name": "actionlink_full_overload_attributes",
"summary": "验证 Html.ActionLink 的全部 8 项参数(linkText/actionName/routeValues/controllerName/htmlAttributes/protocol/hostname/fragment)",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_form_helpers_and_validation_render():
def textbox(name, value=""):
return f'<input id="{name}" name="{name}" type="text" value="{html.escape(value, quote=True)}" />'
def password(name):
return f'<input id="{name}" name="{name}" type="password" />'
def textarea(name, cols=20, rows=2):
return f'<textarea cols="{cols}" id="{name}" name="{name}" rows="{rows}"></textarea>'
def checkbox(name):
return (
f'<input id="{name}" name="{name}" type="checkbox" value="true" />'
f'<input name="{name}" type="hidden" value="false" />'
)
def validation_summary(msg, errors):
if not errors:
return ""
items = "".join(f"<li>{html.escape(e)}</li>" for e in errors)
return f'<div class="validation-summary-errors"><span>{html.escape(msg)}</span><ul>{items}</ul></div>'
form_helpers = [
"BeginForm", "EndForm", "TextArea", "TextBox", "CheckBox",
"RadioButton", "ListBox", "DropDownList", "Hidden", "Password",
]
summary_html = validation_summary("Create was unsuccessful.", ["FirstName is required."])
expected = {
"helper_count": 10,
"textbox": '<input id="FirstName" name="FirstName" type="text" value="" />',
"password_has_no_value_attr": 'value=' not in password("Password"),
"textarea": '<textarea cols="60" id="Profile" name="Profile" rows="10"></textarea>',
"checkbox_has_hidden_false": 'type="hidden" value="false"' in checkbox("ReceiveNewsletter"),
"summary_contains_error": "FirstName is required." in summary_html,
}
actual = {
"helper_count": len(form_helpers),
"textbox": textbox("FirstName"),
"password_has_no_value_attr": 'value=' not in password("Password"),
"textarea": textarea("Profile", cols=60, rows=10),
"checkbox_has_hidden_false": 'type="hidden" value="false"' in checkbox("ReceiveNewsletter"),
"summary_contains_error": "FirstName is required." in summary_html,
}
return {
"name": "form_helpers_and_validation_render",
"summary": "验证 10 类表单帮助器(含 TextBox/Password/TextArea/CheckBox 隐藏 false 伴生字段)与 ValidationSummary 输出",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_html_helper_vs_tag_helper_equivalence():
helper_out = action_link("Edit Record", "Edit", "Home", route_values={"Id": 3})
tag_helper_out = '<a href="/Home/Edit/3">Edit Record</a>'
expected = {
"outputs_identical": True,
"no_viewstate_field": True,
"rendered": '<a href="/Home/Edit/3">Edit Record</a>',
}
actual = {
"outputs_identical": helper_out == tag_helper_out,
"no_viewstate_field": "__VIEWSTATE" not in helper_out,
"rendered": helper_out,
}
return {
"name": "html_helper_vs_tag_helper_equivalence",
"summary": "验证 MVC HTML Helper 无 ViewState 轻量输出及与 ASP.NET Core Tag Helper 输出 HTML 的等价性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_actionlink_basic_and_route_values(),
case_actionlink_full_overload_attributes(),
case_form_helpers_and_validation_render(),
case_html_helper_vs_tag_helper_equivalence(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。
入口文件:projects/web-pages-mvc-htmlhelpers-lab/explore-mvc-htmlhelpers.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-mvc-htmlhelpers.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3042.zip
课程关联工程包(登记关联55章) · 含当前章节或实例 · mbskycom202612a3037.zip