是否可以在 Razor 页面和 MVC 之间共享 _Layout.cshtml?
Is it possible to share a _Layout.cshtml between razor pages and MVC?
假设我有一个同时具有 Razor 页面和 MVC 页面的 .net 5.0 网站。
也就是说,在Startup.Configure中,我有:
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
});
我有一些页面:
- /Pages/MyRazorPage.cshtml
- /Pages/MyRazorPage.cshtml.cs
其他人如:
- /Controllers/MyMvcController.cs
- /Views/MyMvc/Index.cshtml
有没有办法让他们使用相同的布局?
在 /Pages/Shared/_Layout.cshtml 中创建一个 Razor 布局并在 /Views/Shared/_Layout.cshtml 中创建另一个布局似乎很简单,但是如果您希望两种类型的页面具有相同的布局,这似乎是违反了不要重复自己的原则。
有没有办法在两种类型的页面之间共享一个布局?
作为后续行动 - 将 /Pages/Shared/_Layout.cshtml 复制到 /Views/Shared/_Layout.cshtml(并确保 /Views/_ViewStart.cshtml 已设置)有效,除了 asp -page 助手不起作用。使用纯 href= 设置 URL 工作正常。
是的,这是 possible.For 示例,您在 /Pages/Shared/_Layout.cshtml
中有一个布局。并且您想使用它在视图中设置布局。
像这样更改 Views/Shared/_ViewStart.cshtml
:
@{
Layout = "~/Pages/Shared/_Layout.cshtml";
}
这样页面和视图中的布局都将是 /Pages/Shared/_Layout.cshtml
。
假设我有一个同时具有 Razor 页面和 MVC 页面的 .net 5.0 网站。
也就是说,在Startup.Configure中,我有:
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
});
我有一些页面:
- /Pages/MyRazorPage.cshtml
- /Pages/MyRazorPage.cshtml.cs
其他人如:
- /Controllers/MyMvcController.cs
- /Views/MyMvc/Index.cshtml
有没有办法让他们使用相同的布局?
在 /Pages/Shared/_Layout.cshtml 中创建一个 Razor 布局并在 /Views/Shared/_Layout.cshtml 中创建另一个布局似乎很简单,但是如果您希望两种类型的页面具有相同的布局,这似乎是违反了不要重复自己的原则。
有没有办法在两种类型的页面之间共享一个布局?
作为后续行动 - 将 /Pages/Shared/_Layout.cshtml 复制到 /Views/Shared/_Layout.cshtml(并确保 /Views/_ViewStart.cshtml 已设置)有效,除了 asp -page 助手不起作用。使用纯 href= 设置 URL 工作正常。
是的,这是 possible.For 示例,您在 /Pages/Shared/_Layout.cshtml
中有一个布局。并且您想使用它在视图中设置布局。
像这样更改 Views/Shared/_ViewStart.cshtml
:
@{
Layout = "~/Pages/Shared/_Layout.cshtml";
}
这样页面和视图中的布局都将是 /Pages/Shared/_Layout.cshtml
。