MVC Html.DisplayFor for Lists of Derived Models(MVC Html.DisplayFor 用于派生模型列表)
问题描述
假设我有三个类:Derived1ViewModel、Derived2ViewModel 和 BaseViewModel,它们是 Derived1ViewModel的超类code> 和 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>code> 或 List
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> 或 ListList<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 解决了问题.这样,我可以将任何派生类型传递给模板(例如: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 用于派生模型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MVC Html.DisplayFor 用于派生模型列表
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
