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

Blazor Server项目嵌套文件夹_Layout.cshtml不生效问题咨询

Blazor Server嵌套文件夹布局不生效的问题解决

你混淆了Blazor组件布局和ASP.NET Core Razor Pages/MVC布局的机制,这是核心错误:

  • Blazor组件(.razor文件)的布局是通过**Blazor布局组件(.razor格式)**实现的,不是用_Layout.cshtml(这是给Razor Pages/MVC用的)。
  • _Host.cshtml里的@{ Layout = "_Layout"; }是指定服务器端宿主页面的布局,和Blazor组件内部的布局是两层独立的东西。

正确操作步骤

  1. 在Pages/Test文件夹下创建Blazor布局组件,命名为TestLayout.razor,内容参考默认的MainLayout.razor,修改你需要的样式:
@inherits LayoutComponentBase

<div class="test-layout">
    @Body
</div>

<style>
    .test-layout {
        /* 自定义样式 */
        background-color: #f0f0f0;
        padding: 20px;
    }
</style>
  1. 让Test文件夹下的组件使用这个布局,二选一即可:

    • 方法一:在Test文件夹创建_Imports.razor文件,添加全局布局指定,该文件夹下所有组件自动使用:
      @layout TestLayout
      
    • 方法二:直接在Counter.razor顶部添加布局指令:
      @page "/test/counter"
      @layout TestLayout
      
      <!-- 原有组件内容 -->
      
  2. 删除Test文件夹里的_Layout.cshtml,这个文件对Blazor组件没有作用。

这样操作后,访问/test/counter就会使用你自定义的TestLayout布局了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:16:00