假设我有两个类,一个基类:
public class BaseModel {
}
还有几个 child :
public class FooModel : BaseModel {
}
public class BarModel : BaseModel {
}
现在我的观点是我希望有一个这样的模型:
@model IList<BaseModel>
这样我就可以在一页上编辑这些模型。
但是,当我在操作中传递这些模型的集合时,我收到一个异常:
The model item passed into the dictionary is of type 'System.Collections.Generic.List
1[BarModel]', but this dictionary requires a model item of type 'System.Collections.Generic.IList
1[BaseModel]'.
像这样:
var models = new List<BaseModel>(){ new BarModel(), new FooModel ()}
return View(models);
我怎样才能实现这个目标?
谢谢
最佳答案
假设您不修改页面上的模型集合,您的页面不应采用 IList<T>
。相反,它应该需要 IEnumerable<T>
:
@model IEnumerable<BaseModel>
这应该可以解决问题。
关于c# - 将模型传递给 View 时可以向下转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13113249/