📘 第3章:ASP.NET Web Pages 页面布局(Layout)

📌 什么是 Layout 页面?

Layout 页面(通常命名为 _Layout.cshtml)是一个包含网页通用结构的模板页面,如网站的头部、导航栏、底部等内容,其他页面通过 @Layout 指令引用它,实现代码复用和一致性的外观设计。

📁 目录结构建议

/Pages
  |_ _Layout.cshtml        # 通用模板
  |_ Index.cshtml          # 首页
  |_ Contact.cshtml        # 联系页面

🧩 创建一个简单的 Layout 页面

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@Page.Title</title>
    <link rel="stylesheet" href="/Styles/site.css" />
</head>
<body>
    <header>
        <h1>My Website</h1>
        <nav>
            <a href="/Index">Home</a> |
            <a href="/Contact">Contact</a>
        </nav>
    </header>
    <main>
        @RenderBody()
    </main>
    <footer>
        <p>&copy; @DateTime.Now.Year - My Website</p>
    </footer>
</body>
</html>

  • @Page.Title:动态标题(在子页面中设置)
  • @RenderBody():占位符,用于插入子页面内容

📄 在页面中使用 Layout

Index.cshtml

@{
    Layout = "_Layout.cshtml";
    Page.Title = "Home Page";
}
<h2>Welcome to the home page!</h2>
<p>This is the main content of the page.</p>

Contact.cshtml

@{
    Layout = "_Layout.cshtml";
    Page.Title = "Contact Us";
}
<h2>Contact</h2>
<p>Send us an email at contact@example.com.</p>

🎨 页面统一风格(CSS)

/Styles/site.css

body {
    font-family: Arial;
    margin: 0;
    padding: 0;
}

header, footer {
    background-color: #eee;
    padding: 20px;
    text-align: center;
}

nav a {
    margin: 0 10px;
}

引用方式:

<link rel="stylesheet" href="/Styles/site.css" />


✅ 多布局支持(可选)

可以创建多个 Layout 页面,根据页面需要选择引用:

@{
    Layout = "_AdminLayout.cshtml"; // 管理后台专用布局
}


🚨 注意事项

  • Layout 页面必须包含 @RenderBody(),否则子页面内容无法显示
  • 不建议在 Layout 中直接引用页面特有资源,应以通用性为主
  • 布局文件通常放在网站根目录或 /Pages 文件夹下,命名为 _Layout.cshtml 以便识别

🌐 出站链接推荐

📚 参考资料

  1. Microsoft Learn – ASP.NET Web Pages Layout
  2. 《Web Development with ASP.NET Web Pages》章节:Layout & Templates
  3. Stack Overflow 相关话题:asp.net-webpages + layout