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>
或 List
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
解决了问题.这样,我可以将任何派生类型传递给模板(例如: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 用于派生模型列表
基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01