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组件内部的布局是两层独立的东西。
正确操作步骤
- 在Pages/Test文件夹下创建Blazor布局组件,命名为
TestLayout.razor,内容参考默认的MainLayout.razor,修改你需要的样式:
@inherits LayoutComponentBase <div class="test-layout"> @Body </div> <style> .test-layout { /* 自定义样式 */ background-color: #f0f0f0; padding: 20px; } </style>
让Test文件夹下的组件使用这个布局,二选一即可:
- 方法一:在Test文件夹创建
_Imports.razor文件,添加全局布局指定,该文件夹下所有组件自动使用:@layout TestLayout - 方法二:直接在
Counter.razor顶部添加布局指令:@page "/test/counter" @layout TestLayout <!-- 原有组件内容 -->
- 方法一:在Test文件夹创建
删除Test文件夹里的
_Layout.cshtml,这个文件对Blazor组件没有作用。
这样操作后,访问/test/counter就会使用你自定义的TestLayout布局了。
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

