You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Razor页面构建分层布局,实现样式脚本复用与布局控制

Razor页面布局拆分实现方案:全局样式脚本复用+子布局带导航

第一步:创建全局布局_Shared_GlobalLayout.cshtml

这个布局只保留基础HTML框架、所有样式表和JavaScript资源,让需要复用这些资源但不需要导航、页脚的页面直接使用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - xmc.Alliance.CementTrans.Web</title>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/xmc.Alliance.CementTrans.Web.styles.css" asp-append-version="true" />
</head>
<body>
    <!-- 直接渲染页面主体,无导航、页脚 -->
    @RenderBody()

    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>

    @await RenderSectionAsync("Scripts", required: false)
</body>
</html>

第二步:创建带导航栏的子布局_Shared_Layout.cshtml

这个布局继承全局布局,添加导航栏、页脚和主体容器,供需要这些元素的页面使用:

@{
    Layout = "_Shared_GlobalLayout";
}

<header>
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container">
            <!-- 保留原导航栏的内容,比如logo、菜单等 -->
            ...           
        </div>
    </nav>
</header>
<div class="container">
    <main role="main" class="pb-3">
        @RenderBody()
    </main>
</div>

<footer class="border-top footer text-muted">
    <div class="container">
        &copy; 2022 - xmc.Alliance.CementTrans.Web - <a asp-area="" asp-page="/Privacy">Privacy</a>
    </div>
</footer>

第三步:页面布局的使用方式

  • 普通页面(需要导航页脚):默认使用_Shared_Layout.cshtml即可,或在页面顶部显式指定:
    @{
        Layout = "_Shared_Layout";
    }
    
  • 登录页/自定义页面(无需导航页脚):直接指定全局布局,就能复用样式脚本同时排除导航页脚:
    @{
        Layout = "_Shared_GlobalLayout";
    }
    <!-- 页面内容 -->
    

内容的提问来源于stack exchange,提问作者Carrie Kaski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 05:00:54