如何通过模型继承在 ASP.Net Core Razor 页面中使用 DisplayTemplates?

2024-04-25

尝试让 ASP.Net Core 2.2 中的 DisplayTemplates 与从类似于此问题的基类继承的类一起使用如何在视图中处理具有继承的实体模型? https://stackoverflow.com/questions/10473419/how-to-handle-an-entity-model-with-inheritance-in-a-view

The PrincipalDisplayTemplate 用于列表中的所有项目,我缺少什么?

页面模型

public class IndexModel : PageModel
{
    public List<Principal> Principals { get; set; } = new List<Principal>();

    public void OnGet()
    {
        Principals.Add(new Principal { Id = 1, Name = "Principal 1" });
        Principals.Add(new UserPrincipal { Id = 1, Name = "User 1", Age = 30 });
        Principals.Add(new GroupPrincipal { Id = 1, Name = "Group 1", Members = 5 });
        Principals.Add(new UserPrincipal { Id = 1, Name = "User 2", Age = 40 });
        Principals.Add(new GroupPrincipal { Id = 1, Name = "Group 2", Members = 3 });
    }
}

public class Principal
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class UserPrincipal : Principal
{
    public int Age { get; set; }
}

public class GroupPrincipal : Principal
{
    public int Members { get; set; }
}

剃刀页面

@page
@model IndexModel

@foreach(var principal in Model.Principals)
{
    @Html.DisplayFor(p => principal)
}

〜/Pages/Shared/DisplayTemplates/Principal.cshtml

@model Principal
<div>
    <h4>Principal</h4>
    @Model.Name
</div>

〜/Pages/Shared/DisplayTemplates/UserPrincipal.cshtml

@model UserPrincipal
<div>
    <h4>User</h4>
    @Model.Name, Age @Model.Age
</div>

〜/Pages/Shared/DisplayTemplates/GroupPrincipal.cshtml

@model GroupPrincipal
<div>
    <h4>Group</h4>
    @Model.Name, Members @Model.Members
</div>

原因

主要 DisplayTemplate 用于列表中的所有项目,

这是因为表达式中@Html.DisplayFor(expression) 不会被执行根本不。他们是静态解析反而。

例如,如果我们有一个表达式m.a.b.c where a is null在运行时,@Html.DisplayFor(m => m.a.b.c)仍然能够知道模板c.

既然你是宣告 the Principals作为类型List<Principal>,即使你做了Model.Principals hold UserPrincipal or GroupPrincipal 在运行时,“解析器”仍然对待principal作为基础Principaltype:他们不检查真实类型instance。他们只是静态解析类型.

怎么修

调用时传递模板名称Html.DisplayFor()以便 Html Helper 知道您要使用的真实模板:



@page
@model IndexModel

@foreach (var principal in Model.Principals)
{
    @Html.DisplayFor(p => principal, principal.GetType().Name)
}
  

Demo

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何通过模型继承在 ASP.Net Core Razor 页面中使用 DisplayTemplates? 的相关文章

随机推荐