是否可以在 razor 页面和 MVC 之间共享 _Layout.cshtml?

Jef*_*ege 8 c# asp.net-mvc razor .net-core asp.net-core

假设我有一个 .net 5.0 网站,其中既有 Razor 页面又有 MVC 页面。

也就是说,在 Startup.Configure 中,我有:

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapControllers();
    endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
});
Run Code Online (Sandbox Code Playgroud)

我有一些页面,例如:

  • /Pages/MyRazorPage.cshtml
  • /Pages/MyRazorPage.cshtml.cs

其他人喜欢:

  • /控制器/MyMvcController.cs
  • /Views/MyMvc/Index.cshtml

有没有办法让它们使用相同的布局?

在 /Pages/Shared/_Layout.cshtml 中创建一个 Razor 布局并在 /Views/Shared/_Layout.cshtml 中创建另一个 Razor 布局似乎很简单,但是如果您想为两种类型的页面拥有相同的布局,这似乎违反了不要重复自己的原则。

有没有办法在两种类型的页面之间共享单一布局?


正如后续操作一样 - 将 /Pages/Shared/_Layout.cshtml 复制到 /Views/Shared/_Layout.cshtml (并确保设置 /Views/_ViewStart.cshtml)可以工作,但 asp 页面助手不起作用。使用普通的 href= 设置 URL 效果很好。

Yiy*_*You 10

是的,这是可能的。例如,您在 中有一个布局/Pages/Shared/_Layout.cshtml。并且您想用它在视图中设置布局。Views/Shared/_ViewStart.cshtml像这样改变:

@{
    Layout = "~/Pages/Shared/_Layout.cshtml";
}
Run Code Online (Sandbox Code Playgroud)

这样页面和视图中的布局都是/Pages/Shared/_Layout.cshtml.