在 ASP.NET Web Pages 中,布局允许你定义网站的共享外观,并在多个页面之间重用相同的结构和样式。通常,布局包括网站的头部、底部、导航栏等元素。在 ASP.NET Web Pages 中,布局主要通过使用布局页和@RenderSection来实现。

以下是如何在 ASP.NET Web Pages 中使用布局的基本步骤:

1. 创建布局页

在你的项目中创建一个布局页,通常命名为 _Layout.cshtml。这个文件包含了整个网站的共享结构。
<!-- _Layout.cshtml -->

<!DOCTYPE html>
<html>
<head>
    <title>@Page.Title - My Web Site</title>
</head>
<body>
    <header>
        <h1>My Web Site</h1>
    </header>

    <nav>
        <ul>
            <li><a href="/">Home</a></li>
            <li><a href="/about">About</a></li>
            <!-- 添加其他导航链接 -->
        </ul>
    </nav>

    <section>
        @RenderBody()
    </section>

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

在这个例子中,@RenderBody() 表示子页面(使用这个布局的页面)的内容将会渲染在布局的 section 元素中。

2. 使用布局页

在你的子页面(例如 index.cshtml)中指定使用的布局。
<!-- index.cshtml -->
@{
    Layout = "_Layout.cshtml";
    Page.Title = "Home";
}

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

在这个例子中,Layout = "_Layout.cshtml"; 指定了使用名为 _Layout.cshtml 的布局页。

3. 添加部分(Sections)

如果你想在子页面中定制某些部分,可以在布局页中使用 @RenderSection。
<!-- _Layout.cshtml -->

<!-- 在布局页中定义一个 content 部分 -->
<section>
    @RenderBody()
</section>

<!-- 在布局页中定义一个 scripts 部分 -->
<footer>
    &copy; 2023 My Web Site
    @RenderSection("scripts", required: false)
</footer>

在子页面中,你可以通过 @section 定义对应的部分。
<!-- index.cshtml -->
@{
    Layout = "_Layout.cshtml";
    Page.Title = "Home";
}

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

@section scripts {
    <script>
        // Custom scripts for the home page
        console.log("Home page scripts");
    </script>
}

这样,<script> 标签中的内容将会被插入到布局页中定义的 scripts 部分中。

通过使用布局页和部分,你可以更容易地维护和更新你的网站的外观,同时在不同页面之间共享相同的结构和样式。


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