[英]DisplayNameFor a Model child collection
Suppose I have假设我有
class Item {
string Name {get; set;}
int Type {get; set;}
}
If I have my model as a collection of Items, the following compiles:如果我将 model 作为项目集合,则编译如下:
@model IEnumerable<Item>
@Html.DisplayNameFor(model => model.Name)
Now supppose I have changed to this现在假设我已经改为这个
class MyItems {
int Type {get; set;}
IEnumerable<Item> Items {get; set;}
}
this does not compile anymore这不再编译
@model MyItems
@Html.DisplayNameFor(model => model.Items.Name) // NOK
Error CS1061 '
IEnumerable<Item>
' does not contain a definition for 'Name' and no accessible extension method 'Name' accepting a first argument of type 'IEnumerable<Item>
' could be found (are you missing a using directive or an assembly reference?)错误 CS1061“
IEnumerable<Item>
”不包含“Name”的定义,并且找不到接受“IEnumerable<Item>
”类型的第一个参数的可访问扩展方法“Name”(您是否缺少 using 指令或程序集参考?)
I tried我试过了
@Html.DisplayNameFor(model => Model.Items.Name) // _M_odel, NOK
Why the code works in the first case when we have an IEnumerable
, and not the second case, when we have the same IEnumerable
?为什么当我们有一个
IEnumerable
时代码在第一种情况下工作,而不是在我们有相同IEnumerable
的第二种情况下工作?
The first one works because the model is itself of type IEnumerable
while in latter it's the property of main model which is IEnumerable
第一个有效,因为 model 本身是
IEnumerable
类型,而后者是主 model 的属性,它是IEnumerable
The error is pretty self descriptive the Items
property is a collection of Item
so you need to either loop on it or select one of them like:该错误非常具有自我描述性,
Items
属性是Item
的集合,因此您需要对其进行循环或 select 其中一个像:
@Html.DisplayNameFor(model => model.Items.First().Name)
or do like:或喜欢:
@{
var item = model.Items.First();
}
@Html.DisplayNameFor(model => item.Name)
But the First()
will throw exception in case the Items
collection is null or empty.但是如果
Items
集合是 null 或为空, First()
将抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.