【问题标题】:Abstract class implementing PageModel in NET Core RazorPagesNET Core RazorPages 中实现 PageModel 的抽象类
【发布时间】:2020-09-25 04:16:21
【问题描述】:

因此,在 .NET Core 3.1 中使用 Razor 类库 (RCL) 时,我希望有一个预定义的 Index.cshtml 文件。我希望它使用 AbstractIndexModel 作为其模型,但这会给我带来错误。

基本上我想做这样的事情:

这两个在 RCL 中

public abstract class AbstractIndexModel : PageModel
{
    public IActionResult OnGet()
    {
        return Page();
    }

    public abstract string Greeting { get; }
}

剃须刀html

@page
@model AbstractIndexModel

@model.Greeting

然后到应用程序,我们有一个抽象类的实现:

public class IndexModel : AbstractIndexModel
{
    public override string Greeting => "Hello Stackoverflow!";
}

但这只会给出一个错误:

适用于“Sample.Pages.AbstractIndexModel”类型的构造函数 无法定位。确保类型是具体的并且服务是 为公共构造函数的所有参数注册。

我猜这是因为我们设置的模型不是“具体的”(它是一个抽象类)但我想使用@inherit 而不是@model 就可以解决问题。它不是。有什么建议吗?

【问题讨论】:

    标签: c# .net-core asp.net-core-3.1


    【解决方案1】:

    你不能使用抽象类作为@model。它还需要有公共构造函数。 @inherit 也不起作用。

    see@model 和@inherit 的区别

    【讨论】:

    • 该死的。有什么办法可以实现我想要做的事情吗? (或类似的东西)......我想我能真正想到的唯一方法是通过依赖注入......意味着 IndexModel 只是一个类,并将配置作为收缩参数跨度>
    猜你喜欢
    • 2019-06-08
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多