【问题标题】:Why doesn't extending Microsoft.AspNetCore.Mvc.RazorPages.Page class work with layout and partial views?为什么扩展 Microsoft.AspNetCore.Mvc.RazorPages.Page 类不适用于布局和局部视图?
【发布时间】:2020-03-12 00:57:44
【问题描述】:

我正在尝试在所有视图中扩展 Microsoft.AspNetCore.Mvc.RazorPages.Page 以提供额外的功能。扩展 Page 类并在 _ViewImports 中使用 @inherits 在 razor 页面中可以正常工作,但在 _Layout 和部分视图中会出现错误。

我在_ViewImports中添加了以下内容:

@inherits WebApplication1.Razor.CustomRazorPage

地点:

public abstract class CustomRazorPage : Microsoft.AspNetCore.Mvc.RazorPages.Page
{
    public string SayHi(string name)
    {
        return $"Hi <strong>{name}</strong>";
    }
}

但这产生了以下错误:

1>Pages\Shared\_Layout.cshtml(6,13,6,21): error CS0103: The name 'ViewData' does not exist in the current context
1>Pages\Shared\_Layout.cshtml(35,14,35,24): error CS0103: The name 'RenderBody' does not exist in the current context
1>Pages\Shared\_Layout.cshtml(49,7,49,20): error CS0103: The name 'RenderSection' does not exist in the current context

为了解决这个问题,我不得不在_Layout 文件的顶部添加以下内容:

@inherits Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>

但是,我仍然面临部分视图的问题,即使为 RazorPage&lt;TModel&gt;CustomRazorPage 添加显式 @inherits,我也无法获得任何成功:

Error   CS0103  The name 'Model' does not exist in the current context

我已在此 github 存储库中添加了示例代码:aspcore-extend-razor-page-issue(检查 index.cshtml

【问题讨论】:

  • 我用一个 MVC 项目检查了这个问题,它就像一个魅力。我刚刚扩展了Microsoft.AspNetCore.Mvc.Razor.RazorPage&lt;TModel&gt; 并在_ViewImports 中用@inherits 声明了它。 aspcore-extend-razor-page-mvc 中的示例
  • 因此,这个概念适用于 MVC 项目,但不适用于 Razor Pages。

标签: asp.net-mvc asp.net-core razor asp.net-core-mvc razor-pages


【解决方案1】:

事实证明,我们应该为局部视图显式添加@inherits,就像在_Layout文件中一样。所以,部分视图_Hello.cshtml应该如下:

@inherits Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel>
@model WebApplication1.Pages.Models.HelloModel

<div class="alert alert-success">Welcome to our Partial View @Model.Name</div>

但是,在这种情况下,我们将无法从CustomRazorPage 提供的额外功能中受益。但是,我们可以以相同的方式扩展RazorPage&lt;TModel&gt; 以提供与CustomRazorPage 相同的功能。

我不确定是否有其他方法可以解决这个问题。但看起来_Layout 文件和部分视图的上下文与其他 Razor 页面不同。

2019 年 11 月 19 日更新

在我之前发布的这个问题中找到了更多详细信息:

【讨论】:

    猜你喜欢
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 2020-05-25
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多