MVC Html.DisplayFor用于派生模型的列表 [英] MVC Html.DisplayFor for Lists of Derived Models
问题描述
让我们假设我有三个类: Derived1ViewModel
, Derived2ViewModel
和 BaseViewModel
,它们是 Derived1ViewModel 的超类代码>和
Derived2ViewModel
.
Let's assume that I have three classes: Derived1ViewModel
, Derived2ViewModel
and BaseViewModel
which serves as a superclass for the Derived1ViewModel
and Derived2ViewModel
.
我有一个DisplayTemplate,它具有 List< BaseViewModel>
作为模型,我想从使用 List< Derived1ViewModel>作为模型的视图中调用此模板
或 List<Derived2ViewModel>
.
I have a DisplayTemplate which has as a model a List<BaseViewModel>
and I would like to call this template from views which are using as a model a List<Derived1ViewModel>
or a List< Derived2ViewModel>
.
如果我尝试执行此操作,则会触发异常,说它无法将 List< Derived1ViewModel>
或 List< Derived2VIewModel>
转换为 List<BaseViewModel>.
如果我尝试应用诸如 @ Html.DisplayFor(model => model.Cast< BaseViewModel> .ToList(),"MyTemplate")
之类的强制转换,则InvalidOperationException是抛出.
If I try to do this, an exception is triggered saying that it cannot convert a List<Derived1ViewModel>
or List<Derived2VIewModel>
to a List<BaseViewModel>.
If I try to apply a cast such as @Html.DisplayFor(model=>model.Cast<BaseViewModel>.ToList(), "MyTemplate")
an InvalidOperationException is thrown.
详细信息:[InvalidOperationException:模板只能与字段访问,属性访问,一维数组索引或单参数自定义索引器表达式一起使用.]
Details: [InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.]
这个问题可以解决吗,还是采取另一种方法所必需的?
Can this problem be solved or its necessary to take another approach?
推荐答案
通过使用 BaseViewModel
的模板而不是 List< BaseViewModel>
的模板解决了该问题.这样,我可以将任何派生类型传递给模板(例如:Derived1ViewModel,Derived2ViewModel).
Solved the problem by using a template for BaseViewModel
instead of List<BaseViewModel>
. In this way, I can pass any derived type to the template (ex: Derived1ViewModel, Derived2ViewModel).
示例:
@*Derived1 View*@
@model List<Derived1ViewModel>
@for(var i = 0; i < Model.Count; i++)
{
int i1 = i;
@Html.DisplayFor(model=>model[i1], "MyTemplate")
}
@*Derived2 View*@
@model List<Derived2ViewModel>
@for(var i = 0; i < Model.Count; i++)
{
int i1 = i;
@Html.DisplayFor(model=>model[i1], "MyTemplate")
}
@*Template*@
@model BaseViewModel
<p>It works @Model.Name</p>
这篇关于MVC Html.DisplayFor用于派生模型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!