[英]How do I index an ICollection<T> like they tell me to in this example?
I'm trying list items in my MVC view, following this example: Model Binding to a List . 我尝试按照以下示例在MVC视图中列出项目: 模型绑定到List 。 I'm using MVC 5. There example says to do this: 我正在使用MVC5。下面的示例说明如何执行此操作:
<%@ Page Inherits="ViewPage<IList<Book>>" %>
<% for (int i = 0; i < 3; i++) { %>
<%: Html.EditorFor(m => m[i]) %>
<% } %>
I'm trying to do this: 我正在尝试这样做:
for (int i = 0; i < Model.SubmissionTypesSelected.Count(); i++)
{
Html.EditorFor(m => m.SubmissionTypesSelected[i]);
}
SubmissionTypesSelected
is defined like this: SubmissionTypesSelected
定义如下:
public ICollection<PTSubTypeSelected> SubmissionTypesSelected { get; set; }
I get this message: 我收到此消息:
Cannot apply indexing to an expression of type 'System.Collections.Generic.ICollection' 无法将索引应用于类型为'System.Collections.Generic.ICollection'的表达式
The error is kind of self-explanatory; 该错误是不言自明的。 you can't use indexing on an ICollection{T}
because it is designed to be able to modify the contents of a collection of elements, not the order of them. 您不能在ICollection{T}
上使用索引,因为它旨在修改元素集合的内容,而不是元素顺序。 Changing it to a IList{T}
is a simple answer, as the example you've linked does. 就像您链接的示例一样,将其更改为IList{T}
是一个简单的答案。
MVC needs to have indexes added in HTML so it can figure out which property value goes with which item in a collection on postback. MVC需要在HTML中添加索引,以便它可以确定回发时集合中哪个属性值与集合中的哪个项目一起使用。 The EditorFor
will do this for you if you pass it an IEnumerable
of any kind directly. 如果您直接将其传递给任何类型的IEnumerable
,则EditorFor
将为您执行此操作。 So you can just do this: 因此,您可以执行以下操作:
Html.EditorFor(m => m.SubmissionTypesSelected);
It will loop through each item, generate an index for you, and pass the individual item to your editor template. 它将遍历每个项目,为您生成一个索引,并将单个项目传递给您的编辑器模板。
What happens if you do this: 如果执行此操作会发生什么:
var typesArray = Model.SubmissionTypesSelected.ToArray();
for (int i = 0; i < typesArray.Length; i++)
{
Html.EditorFor(m => typesArray[i]);
}
尝试使用CopyTo(Array, Int32)
,然后像通常使用数组一样继续进行迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.