【发布时间】: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<TModel> 或 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<TModel>并在_ViewImports 中用@inherits声明了它。 aspcore-extend-razor-page-mvc 中的示例 -
因此,这个概念适用于 MVC 项目,但不适用于 Razor Pages。
标签: asp.net-mvc asp.net-core razor asp.net-core-mvc razor-pages