MVC Html.DisplayFor 用于派生模型列表

MVC Html.DisplayFor for Lists of Derived Models(MVC Html.DisplayFor 用于派生模型列表)

本文介绍了MVC Html.DisplayFor 用于派生模型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个类:Derived1ViewModelDerived2ViewModelBaseViewModel,它们是 Derived1ViewModelDerived2ViewModel.

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 用于派生模型列表

基础教程推荐