我正在尝试在所有视图中扩展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>
但是,我仍然面临局部视图的麻烦,即使为@inherits
或RazorPage<TModel>
添加显式CustomRazorPage
,我也无法获得成功:
Error CS0103 The name 'Model' does not exist in the current context
我已在此github存储库中添加了示例代码:aspcore-extend-razor-page-issue(选中index.cshtml
)
答案 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页面不同。
在我之前发布的此问题中找到了更多详细信息: