尝试让 ASP.Net Core 2.2 中的 DisplayTemplates 与从类似于此问题的基类继承的类一起使用如何在视图中处理具有继承的实体模型? https://stackoverflow.com/questions/10473419/how-to-handle-an-entity-model-with-inheritance-in-a-view
The Principal
DisplayTemplate 用于列表中的所有项目,我缺少什么?
页面模型
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>