mhe*_*all 6 display-templates asp.net-core
尝试让 ASP.Net Core 2.2 中的 DisplayTemplates 与从基类继承的类一起使用,类似于此问题How to handle anEntity Model with Inheritance in a view?
DisplayTemplatePrincipal
用于列表中的所有项目,我缺少什么?
页面模型
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; }
}
Run Code Online (Sandbox Code Playgroud)
剃刀页面
@page
@model IndexModel
@foreach(var principal in Model.Principals)
{
@Html.DisplayFor(p => principal)
}
Run Code Online (Sandbox Code Playgroud)
〜/Pages/Shared/DisplayTemplates/Principal.cshtml
@model Principal
<div>
<h4>Principal</h4>
@Model.Name
</div>
Run Code Online (Sandbox Code Playgroud)
〜/Pages/Shared/DisplayTemplates/UserPrincipal.cshtml
@model UserPrincipal
<div>
<h4>User</h4>
@Model.Name, Age @Model.Age
</div>
Run Code Online (Sandbox Code Playgroud)
〜/Pages/Shared/DisplayTemplates/GroupPrincipal.cshtml
@model GroupPrincipal
<div>
<h4>Group</h4>
@Model.Name, Members @Model.Members
</div>
Run Code Online (Sandbox Code Playgroud)
主要 DisplayTemplate 用于列表中的所有项目,
那是因为 in 的表达式根本@Html.DisplayFor(expression)
不会被执行。相反,它们是静态解析的。
例如,如果我们在运行时有一个表达式m.a.b.c
where a
is ,则仍然能够知道 的模板。null
@Html.DisplayFor(m => m.a.b.c)
c
由于您将as声明Principals
为type List<Principal>
,即使您在运行时Model.Principals
保留UserPrincipal
or ,“解析器”仍然将 the 视为基本类型:它们不检查实例的真实类型。他们只是静态地解析类型。GroupPrincipal
principal
Principal
调用时传递模板名称,Html.DisplayFor()
以便 Html Helper 知道您要使用的真实模板:
@页 @model索引模型 @foreach(Model.Principals 中的 var 主体) { @Html.DisplayFor(p => 主体,主体.GetType().Name ) }
归档时间: |
|
查看次数: |
4280 次 |
最近记录: |