为什么不扩展Microsoft.AspNetCore.Mvc.RazorPages.Page类可用于布局和局部视图?

时间:2019-11-15 20:38:22

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

我正在尝试在所有视图中扩展Microsoft.AspNetCore.Mvc.RazorPages.Page以提供额外的功能。扩展Page类并在@inherits中使用_ViewImports在剃须刀页面上效果很好,但是_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>

但是,我仍然面临局部视图的麻烦,即使为@inheritsRazorPage<TModel>添加显式CustomRazorPage,我也无法获得成功:

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

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

1 个答案:

答案 0 :(得分: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<TModel>来提供与CustomRazorPage相同的功能。

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

更新11/19/2019

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