M Kenyon II
M Kenyon II

Reputation: 4264

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. I'm using MVC 5. There example says to do this:

<%@ 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:

public ICollection<PTSubTypeSelected> SubmissionTypesSelected { get; set; }

I get this message:

Cannot apply indexing to an expression of type 'System.Collections.Generic.ICollection'

Upvotes: 0

Views: 1973

Answers (3)

Will Ray
Will Ray

Reputation: 10879

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. Changing it to a IList{T} is a simple answer, as the example you've linked does.

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. The EditorFor will do this for you if you pass it an IEnumerable of any kind directly. 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.

Upvotes: 1

Daniel Arechiga
Daniel Arechiga

Reputation: 967

Try using CopyTo(Array, Int32) and then continue to iterate as you would normally do with an array.

Upvotes: 0

Michael Blackburn
Michael Blackburn

Reputation: 3229

What happens if you do this:

var typesArray = Model.SubmissionTypesSelected.ToArray();
for (int i = 0; i < typesArray.Length; i++)
{
    Html.EditorFor(m => typesArray[i]);
}

Upvotes: 0

Related Questions