Razor Pages:继承要在创建过程中添加字段的模型

问题描述 投票:0回答:1

这些实体在虚拟上相当于我要完成的工作(实际上更复杂)。

我仅需要在创建文章(SendToSubscribers字段)时才需要在表单中显示其他字段,而这些字段并不是实体本身的一部分。

public class Article {
    public string Title { get; set }
}

public class ArticleCreateForm : Article {
    public bool SendToSubscribers { get; set; }
}

在cshtml中用于创建/更新的是:

@model Article
...
@if (string.IsNullOrEmpty(Model.Id))
{
    <admin-input asp-for="SendToSubscribers" />

不幸的是,这是我得到的错误:

'Article' does not contain a definition for 'SendToSubscribers' and no accessible extension method 'SendToSubscribers' accepting a first argument of type 'Article' could be found (are you missing a using directive or an assembly reference?)

抱歉,如果方法根本不好,我来自PHP背景。

我想这不是一个好的解决方案,所以我该如何纠正呢?谢谢。

c# razor .net-core
1个回答
0
投票

您的解决方案具有一种与设计模式相关的方法。

创建一个容器类,它将同时占用两个模型:

public class MainArticleModel{
    public Article article{get; set;}
    public ArticleCreateForm articleCreateForm {get; set;}
}

然后您将可以使用它:

@model MainArticleModel
...
@if (string.IsNullOrEmpty(Model.Id))
{
    <admin-input asp-for="SendToSubscribers" />

这样,两个模型都将包含在一个视图中。

© www.soinside.com 2019 - 2024. All rights reserved.