Tro*_*ley 2 c# asp.net asp.net-mvc entity-framework razor
我Customer用两个派生类PrivateCustomer和创建了一个基类BusinessCustomer。这是我的实体模型:
我认为,我需要显示所有客户的列表。但是我也想表明他们是企业客户还是私人客户,并为例如私人客户获取一些特定信息。
我的视图需要模型,@model IEnumerable<CarDealerMVC.Models.Customer>并且它通过控制器从控制器获取模型return View(db.CustomerSet.ToList());
但是,该列表不包含派生对象-仅包含基(Customer)。因此,虽然我可以使用来检查它是企业客户还是私人客户@if (item is Models.PrivateCustomer),但我无法打印PrivateCustomer特定的属性,例如Cpr。
我怎样才能做到这一点?
这可以使用DisplayFor模板来实现,声明@Model每种不同具体元素类型的类型。
例如Shared/DisplayTemplates/PrivateCustomer.cshtml:
@Model PrivateCustomer
@Model.Id
@Model.Name
@Model.Phone
@Model.Cpr
@Model.Genger
Run Code Online (Sandbox Code Playgroud)
和Shared/DisplayTemplates/BusinessCustomer.cshtml:
例如Shared/DisplayTemplates/BusinessCustomer.cshtml:
@Model BusinessCustomer
@Model.Id
@Model.Name
@Model.VatNumber
@Model.Fax
Run Code Online (Sandbox Code Playgroud)
然后在您的视图中,您需要按如下所示循环收集,使用反射在运行时定位模板:
@foreach(var item in Model)
{
@Html.DisplayFor(x => item, item.GetType().Name)
}
Run Code Online (Sandbox Code Playgroud)
这样抽象了特定的具体实例,但不幸的是意味着你的公共基础性,即重复Id,Name等等。