[英]How to use Derived type of a collection as ViewModel in Asp.Net MVC?
我有一个强类型的视图,视图(简化)如下所示。
@model List<PatientCategory>
<table class="table table-striped table-bordered">
<tr>
<th>
@Html.DisplayNameFor(model => model.Code)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th>
@Html.DisplayNameFor(model => model.ModifiedTime)
</th>
<th>
@Html.DisplayNameFor(model => model.History)
</th>
<th>Edit</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Code)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.ModifiedTime)
</td>
<td>
@Html.DisplayFor(modelItem => item.History)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
这很好。
但是现在我想将View模型更改为另一个类型PaginatedList<short>
,它是从List<PatientCategory>
派生的,如下所示PaginatedList<PatientCategory> : List<PatientCategory>
但是,当我将@model IEnumerable<PatientCategory>
替换为@model IEnumerable<PatientCategory>
@model PaginatedList<PatientCategory>
,助手@Html.DisplayNameFor()
无效。 有人可以建议我一些办法。 我发现可以使用@Html.DisplayName("Code")
,但是我想知道还有更好的选择吗?
DisplayNameFor
能够查看基础类型,使您可以绑定到仅适用于IEnumerable
的属性。 即使您要使视图的模型为List<PatientCategory>
而不是IEnumerable<PatientCategory>
,它也会失败。
您可以采用的一种解决方法是简单地为列表建立索引:
@Html.DisplayNameFor(model => model[0].Code)
索引本身并不重要,因为Html.DisplayNameFor
只是解析表达式以查看它需要获取PatientCategory.Code
的显示名称,它实际上从未尝试访问列表的第一项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.