我有一个类,其中包含一个属性作为另一个对象的列表
public class MyObject {
public MyObject()
{
this.Items = new List<Item>
{
new Item(),
new Item()
};
}
public List<Item> Items { get; set; }
}
}
public class Item
{
public double ItemSetting { get; set; }
[CompareIf("ItemSetting", Operator.LessThanOrEqual, ErrorMessageResourceType = typeof(UiResources), ErrorMessageResourceName = "ItemMinError")]
public double ItemMin { get; set; }
}
我正在尝试在模板中显示列表:
@model IEnumerable<Web.Models.Item>
@{
}
通过:
@model Web.Models.MyObject
@{
@Html.EditorFor(x => x.Items)
}
但我收到错误:
The model item passed into the dictionary is of type 'Web.Models.MyObject', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Web.Models.Item]'.
我正在向编辑器模板传递一个 List 类型的属性,那么为什么它会将其作为单个 Item 类型获取?
在项目模板中,我需要显示一个标题,该标题告诉列表中项目的索引。例如:
<h3>Item 1</h3>
@Html.TextBoxFor(x => x.ItemSetting })
下一个项目:
<h3>Item 2</h3>
@Html.TextBoxFor(x => x.ItemSetting })
(记住我在 MyObject 构造函数中创建了 2 个空项目)
如果我只在项目模板中显示一项,如何获取相关索引?
最佳答案
您收到此错误的原因是您的模型的值为 null
(因此 model.Items
是 null
)因此默认情况下,它将主模型传递给模板。您需要确保将模型的实例传递给 GET 方法中的 View 。
但是主视图中的方法应该是
@model Web.Models.Item
不是 @model IEnumerable<Web.Models.Item>
。该方法接受 IEnumerable<T>
并且足够智能,可以根据模板中的 html 为集合中的每个项目生成 html
关于asp.net-mvc - EditorFor ListView 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31695898/