【问题标题】:Is it possible to share a _Layout.cshtml between razor pages and MVC?是否可以在剃刀页面和 MVC 之间共享 _Layout.cshtml?
【发布时间】:2021-07-15 02:17:21
【问题描述】:

假设我有一个包含 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 可以正常工作。

【问题讨论】:

  • 您好,我的回答有用吗?

标签: c# asp.net-mvc asp.net-core .net-core razor


【解决方案1】:

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

@{
    Layout = "~/Pages/Shared/_Layout.cshtml";
}

这样 Pages 和 Views 中的布局都是/Pages/Shared/_Layout.cshtml

【讨论】:

    猜你喜欢
    • 2010-10-24
    • 2022-01-09
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 2015-07-13
    相关资源
    最近更新 更多