MVC 视图
系统讲解 ASP.NET MVC Views 文件夹子目录组织、5 类历史与现代视图文件扩展名、Index.cshtml 与 About.cshtml 的 ViewBag.Title 渲染流程以及首次调试运行验证要点。
学完这一章,你能够
- 系统讲解 ASP.NET MVC Views 文件夹子目录组织、5 类历史与现代视图文件扩展名、Index.cshtml 与 About.cshtml 的 ViewBag.Title 渲染流程以及首次调试运行验证要点。
Views 文件夹结构与 ASP.NET 常见文件类型
在 MvcDemo 实战第 5 部分中,我们编写用于界面呈现的视图文件。`Views` 文件夹集中存放决定用户界面外观的标记文件(依据选用引擎不同,历史上可见 `.html`、`.asp`、`.aspx`、`.cshtml` 或 `.vbhtml` 扩展名),并按控制器名称建立子目录:模板默认创建的 `Account` 目录存放用户注册与登录视图,`Home` 目录存放首页与关于页视图,`Shared` 目录存放跨控制器共用的母版布局页与通用视图。
在传统 ASP.NET 项目中,可能遇到五类常见的网页/视图扩展名(见下表)。需注意在现代 ASP.NET Core MVC 中,经典 ASP(`.asp`)、Web Forms(`.aspx`)与 VB Razor(`.vbhtml`)均已退出主流,应用视图统一使用 C# Razor 文件 `.cshtml`,并通过 `@model` 指令声明强类型视图模型以获得编译期检查与智能提示。
编写 Index.cshtml 与 About.cshtml 并运行调试
`Views/Home/Index.cshtml` 是应用程序的默认首页视图。我们在文件顶部通过 Razor 代码块设置 `@{ ViewBag.Title = "Home Page"; }`(该值会自动填入 `_Layout.cshtml` 的 `<title>@ViewBag.Title</title>`),随后编写首页主标题 `<h1>Welcome to MvcDemo</h1>` 与正文段落 `<p>Put Home Page content here</p>`。
`Views/Home/About.cshtml` 对应“关于”页面,结构与首页一致:先设定 `@{ ViewBag.Title = "About Us"; }`,再输出 `<h1>About Us</h1>` 与正文介绍段落;两者均由 `_ViewStart.cshtml` 自动套用 `_Layout.cshtml` 共享外壳。
完成控制器与视图编写后,在 Visual Studio / Visual Web Developer 中点击 `Debug -> Start Debugging`(快捷键 `F5`;在现代 ASP.NET Core CLI 中运行 `dotnet run` 或 `dotnet watch`)即可启动本地服务器并在浏览器中预览。此时点击顶部导航栏的 `Home` 与 `About` 标签页可正常切换并显示对应标题与内容,标志着首个 MVC 应用程序已成功跑通;而 `Movies` 标签页因尚未创建 `MoviesController` 与数据模型暂不可访问,将在后续数据库与模型章节中补齐。
ASP.NET 常见视图与网页文件扩展名对照
| 文件类型 | 文件扩展名 | 技术演进与适用说明 |
| 纯 HTML | .htm / .html | 静态超文本文件,不含服务器端代码执行。 |
| 经典 ASP | .asp | 早期 Active Server Pages 脚本页,已属历史维护技术。 |
| 经典 ASP.NET | .aspx | 传统 ASP.NET Web Forms 页面及早期 ASPX 视图引擎扩展名。 |
| ASP.NET Razor C# | .cshtml | 现代 ASP.NET MVC 与 ASP.NET Core MVC/Razor Pages 的标准 C# 视图扩展名。 |
| ASP.NET Razor VB | .vbhtml | 传统 .NET Framework Razor VB 视图扩展名,ASP.NET Core 已不再支持。 |
离线校验 Razor 视图查找回退顺序、5 类文件扩展名及 Index/About 渲染与路由可达性
展开查看收起
"""Offline ASP.NET MVC views verification lab for Chapter 31 (mvc-views)."""
import html
import json
VERSION = "CPython 3.12.14 offline ASP.NET MVC Razor view engine semantic verifier (IIS/ASP.NET host absent)"
def case_views_folder_and_search_order():
existing = {
"Views/Account/LogOn.cshtml",
"Views/Account/Register.cshtml",
"Views/Home/Index.cshtml",
"Views/Home/About.cshtml",
"Views/Shared/_Layout.cshtml",
"Views/Shared/Error.cshtml",
}
def find_view(controller, view_name):
candidates = [
f"Views/{controller}/{view_name}.cshtml",
f"Views/Shared/{view_name}.cshtml",
]
for path in candidates:
if path in existing:
return path
return None
expected = {
"home_index": "Views/Home/Index.cshtml",
"home_about": "Views/Home/About.cshtml",
"shared_fallback": "Views/Shared/Error.cshtml",
"missing_movies": None,
}
actual = {
"home_index": find_view("Home", "Index"),
"home_about": find_view("Home", "About"),
"shared_fallback": find_view("Home", "Error"),
"missing_movies": find_view("Movies", "Index"),
}
return {
"name": "views_folder_and_search_order",
"summary": "模拟 Razor 视图引擎按 Views/{Controller}/{Action}.cshtml 到 Views/Shared/{Action}.cshtml 的回退查找顺序",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_aspnet_view_file_extensions_table():
file_types = [
("纯 HTML", [".htm", ".html"]),
("经典 ASP", [".asp"]),
("经典 ASP.NET", [".aspx"]),
("ASP.NET Razor C#", [".cshtml"]),
("ASP.NET Razor VB", [".vbhtml"]),
]
expected = {
"type_count": 5,
"razor_cs_ext": ".cshtml",
"razor_vb_ext": ".vbhtml",
"core_supported_razor": [".cshtml"],
}
actual = {
"type_count": len(file_types),
"razor_cs_ext": file_types[3][1][0],
"razor_vb_ext": file_types[4][1][0],
"core_supported_razor": [ext for name, exts in file_types if "Razor C#" in name for ext in exts],
}
return {
"name": "aspnet_view_file_extensions_table",
"summary": "核对 Views 文件夹中 5 类 HTML/ASP.NET 扩展名及 ASP.NET Core 仅保留 .cshtml 的演进规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_index_and_about_viewbag_render():
def render_with_layout(viewbag_title, h1_text, p_text):
return (
f"<title>{html.escape(viewbag_title)}</title>"
f"<section id=\"main\"><h1>{html.escape(h1_text)}</h1><p>{html.escape(p_text)}</p></section>"
)
index_html = render_with_layout("Home Page", "Welcome to MvcDemo", "Put Home Page content here")
about_html = render_with_layout("About Us", "About Us", "Put About Us content here")
expected = {
"index_title_ok": "<title>Home Page</title>" in index_html,
"index_h1_ok": "<h1>Welcome to MvcDemo</h1>" in index_html,
"about_title_ok": "<title>About Us</title>" in about_html,
"about_h1_ok": "<h1>About Us</h1>" in about_html,
}
actual = {
"index_title_ok": "<title>Home Page</title>" in index_html,
"index_h1_ok": "<h1>Welcome to MvcDemo</h1>" in index_html,
"about_title_ok": "<title>About Us</title>" in about_html,
"about_h1_ok": "<h1>About Us</h1>" in about_html,
}
return {
"name": "index_and_about_viewbag_render",
"summary": "验证 Index.cshtml 与 About.cshtml 通过 ViewBag.Title 向 _Layout.cshtml 传递标题并渲染正文",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_unwired_movies_route_status():
registered_controllers = {"Home": {"Index", "About"}, "Account": {"LogOn", "Register"}}
def simulate_click(controller, action="Index"):
if controller not in registered_controllers or action not in registered_controllers[controller]:
return 404
return 200
expected = {"home_status": 200, "about_status": 200, "movies_status_before_model": 404}
actual = {
"home_status": simulate_click("Home", "Index"),
"about_status": simulate_click("Home", "About"),
"movies_status_before_model": simulate_click("Movies", "Index"),
}
return {
"name": "unwired_movies_route_status",
"summary": "验证首次运行 MvcDemo 时 Home/About 可达(200),而尚未创建 MoviesController 的 Movies 标签返回 404",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_views_folder_and_search_order(),
case_aspnet_view_file_extensions_table(),
case_index_and_about_viewbag_render(),
case_unwired_movies_route_status(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
默认先查找 `Views/Home/About.cshtml`;若未找到,再回退查找 `Views/Shared/About.cshtml`;若仍不存在则抛出视图未找到异常。