Asp.net mvc Razor DisplayFor()不会在集合上迭代(但EditorFor()会迭代!)

Asp.net mvc Razor DisplayFor()不会在集合上迭代(但EditorFor()会迭代!),asp.net-mvc,razor,Asp.net Mvc,Razor,我(不正确?)的理解是,调用@Html.DisplayFor(x=>x.SomeCollection)应该自动迭代集合,并调用SomeCollection中元素的显示模板。然而,我看到的是一个例外: 传递到字典中的模型项的类型为 'System.Collections.Generic.List`1[Abc.Services.Crm.Dtos.Crmpersondo+ViewModelDataClass+UserRoleSelected], 但此词典需要类型为的模型项 'Abc.Services.

我(不正确?)的理解是,调用
@Html.DisplayFor(x=>x.SomeCollection)
应该自动迭代集合,并调用
SomeCollection
中元素的显示模板。然而,我看到的是一个例外:

传递到字典中的模型项的类型为 'System.Collections.Generic.List`1[Abc.Services.Crm.Dtos.Crmpersondo+ViewModelDataClass+UserRoleSelected], 但此词典需要类型为的模型项 'Abc.Services.Crm.Dtos.CrmPersonDto+ViewModelDataClass+UserRoleSelected'

如您所见,传递到我的显示模板的模型是整个
列表
项,而不是单个元素

另一方面,如果我调用编辑器模板,我似乎得到了自动迭代,只有使用
DisplayFor()
(和Display模板)我才能得到异常。当我在集合上手动调用
@foreach()
时,我的显示模板被调用为刚刚好

这是我的显示模板(请不要评论VM类结构。我知道它需要修复):


您需要删除
DisplayFor()
的第二个参数。添加
templateName
时,您告诉方法将模型(一个
列表
)传递到该模板(该模板只接受
UserRoleSelected
的一个实例),因此会出现错误

如果没有
templateName
,该方法将迭代集合中的每个项,并将每个实例传递给模板以生成html

你的代码应该是

@model Abc.Services.Crm.Dtos.CrmPersonDto
... more stuff ...
@Html.DisplayFor(m => m.UserRolesSelected)

注意:这假定
UserRoleSelected.cshtml
部分位于
/Views/Shared/DisplayTemplates
(或
/Views/yourcontrolername/DisplayTemplates
)文件夹中

如果是这样的话,那么为什么我使用EditorFor()会工作得很好呢?使用
EditorFor(m=>m.userrolelessected,“userrolelected”)
(假设你的
EditorTemplate
for
userrolelected
已经
@model userrolelected
)。您将得到完全相同的错误。我不知道你为什么声称它有效。
@model Abc.Services.Crm.Dtos.CrmPersonDto
   ... more stuff ...
@Html.DisplayFor(m => m.UserRolesSelected, "UserRoleSelected") // causes exception!
@model Abc.Services.Crm.Dtos.CrmPersonDto
... more stuff ...
@Html.DisplayFor(m => m.UserRolesSelected)