Click here to Skip to main content
15,884,176 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more: , +
problem
cannot apply index with [ ] to an expression of type Icollection mvc view asp.net core 2.1
public class SalesHeader
    {
        public SalesHeader()
        {

        }
        public int SalesYear { get; set; }
        public int BranchCode { get; set; }
        public ICollection<SalesFooter> SalesFooters { get; set; }
    }


What I have tried:

@for (var i = 0; i < Model.SalesFooters.Count; ++i)
                   {
                       <tr>
                           <td>
                               @Html.EditorFor(f => f.SalesFooters[i].ItemCode)
                           </td>
                           <td>
                               @Html.EditorFor(f => f.SalesFooters[i].Quantity)
                           </td>
                           <td>
                               @Html.EditorFor(f => f.SalesFooters[i].UnitPrice)
                           </td>
                       </tr>
                   }


it show my in for loop above compile error
cannot apply index with [ ] to an expression of type Icollection mvc view asp.net core 2.1

How to solve this error please ?
Posted
Updated 14-Feb-19 2:55am

ICollection is the base interface for all Collection classes in .NET: ICollection Interface (System.Collections) | Microsoft Docs[^]
Which means that IList is derived from ICollection, not the other way around. IList supports indexing, but ICollection does not.

An object that implements IList can be stored in an ICollection variable, but you cannot use IList methods (or indexers) on it without casting it to a IList (which may fail, because not every ICollection object is an IList).
 
Share this answer
 
v2
The ICollection interface doesn't have a [] indexer defined. You cannot use it like an array.

It does, however, support enumeration. In your case, you can just swap out the for loop with foreach and use the enumerator instead:
C#
@foreach (var footer in Model.SalesFooters)
{
    <tr>
        <td>
            @Html.EditorFor(f => footer.ItemCode)
        </td>
        <td>
            @Html.EditorFor(f => footer.Quantity)
        </td>
        <td>
            @Html.EditorFor(f => footer.UnitPrice)
        </td>
    </tr>
}
 
Share this answer
 
Comments
F-ES Sitecore 14-Feb-19 9:01am    
Model binding doesn't work with that technique though, you need to use array indexers which is where I imagine the initial problem is coming from.
Dave Kreskowiak 14-Feb-19 10:18am    
Kind of odd that it works perfectly fine for me, though I'm using the full framework, not Core.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900