在 ASP.NET Web Pages 中,布局是一种将通用的 HTML 结构与具体页面内容分离的技术。布局允许你定义一次性的外观,并在多个页面中共享它,以提高代码的可维护性和可重用性。在 Web Pages 中,布局通常使用 _Layout.cshtml 文件,这个文件包含页面的共享结构。

以下是 ASP.NET Web Pages 中布局的基本概念和示例:

1. 创建布局文件 _Layout.cshtml:
<!-- _Layout.cshtml -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@PageData["Title"] - My Web Pages</title>
</head>
<body>
    <header>
        <h1>My Web Pages</h1>
    </header>

    <div id="content">
        @RenderBody()
    </div>

    <footer>
        &copy; 2023 My Web Pages
    </footer>
</body>
</html>

在上述布局文件中,@RenderBody() 用于表示页面具体内容的呈现位置。@PageData["Title"] 用于显示页面的标题,这个标题会在具体页面中设置。

2. 在具体页面中使用布局:
@{
    Layout = "_Layout.cshtml";
    PageData["Title"] = "Home";
}

<h2>Welcome to the Home Page</h2>
<p>This is the content of the home page.</p>

在具体的页面中,通过 Layout = "_Layout.cshtml"; 指定页面使用的布局文件。同时,通过 PageData["Title"] = "Home"; 设置页面的标题,这个标题会在布局文件中使用。

3. 部分视图(Sections):

在布局文件和具体页面中,可以使用部分视图来定义和使用各自的内容块。这使得每个页面能够定义自己的特定内容,而不影响整体布局。

在布局文件中使用 @RenderSection 定义一个可选的内容块:
<!-- _Layout.cshtml -->
<body>
    <header>
        <h1>My Web Pages</h1>
    </header>

    <div id="content">
        @RenderSection("Content", required: false)
        @RenderBody()
    </div>

    <footer>
        &copy; 2023 My Web Pages
    </footer>
</body>

在具体页面中使用 @section 定义特定的内容块:
@{
    Layout = "_Layout.cshtml";
    PageData["Title"] = "Home";
}

@section Content {
    <h2>Welcome to the Home Page</h2>
    <p>This is the content of the home page.</p>
}

这里,@RenderSection("Content", required: false) 表示在布局中的 Content 区域将呈现具体页面中定义的内容。

通过布局和部分视图的使用,ASP.NET Web Pages 提供了一种简单而强大的方式来管理页面的共享结构和特定内容。


转载请注明出处:http://www.pingtaimeng.com/article/detail/14782/ASP.NET Web Pages