c# - 将模型传递给 View 时可以向下转换吗?

标签 c# asp.net-mvc

假设我有两个类,一个基类:

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.List1[BarModel]', but this dictionary requires a model item of type 'System.Collections.Generic.IList1[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/

相关文章:

.NET 5.0 上 Outlook Automation 的 C# Marshal.GetActiveObject() 替代方案

c# - 使用 C# try/catch/finally 表现得像 if/else 的最佳方式是什么?

asp.net-mvc - 为什么应该将 WCF 与 MVC 结合使用?

c# - 如何最好地处理包含 0 到 3 个参数/过滤器但使用单个 LinQ to Entities 表达式的搜索查询

c# - MessageBox、C#、Windows 窗体未使用的输入键

c# - 如何将按钮添加到 Visual Studio Intellisense

c# - 在 .net 4 中获取连接字符串

.net - Quartz.net:预定的代码在部署后不自动工作,在本地工作

jquery - 更新标签表后刷新 tag-it 中的数据

JavaScript/jQuery 不适用于使用 Ajax 加载的编辑器/显示模板