locked
Cannot apply index with [ ] to an expression of type icollection MVC view ASP.NET core 2.1 RRS feed

  • Question

  • problem
    cannot apply index with [ ] to an expression of type Icollection mvc view asp.net core 2.1 

    Code:

    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:

    Code:

    @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

    Place Of ERROR

    the error show on view Edit under f.salesfooter[i] on for loop because indexing is applied to list

    and i use collection 

    my question How to convert collection to list 
    or 
    How using indexing in collection ?
    Friday, February 15, 2019 1:30 AM

All replies

  • cannot apply index with [ ] to an expression of type Icollection mvc view asp.net core 2.1

    An ICollection cannot be addressed by an [] indexer. The property would need to be changed to a List<t>.

    https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.icollection-1?redirectedfrom=MSDN&view=netframework-4.7.2

    <copied>

     A IList<T> implementation is a collection of values, and its members can be accessed by index, like the List<T> class.

    <end>

    If the class is a virtual model object used by EF, then maybe,  it's best to use a viewmodel and send the viewmodel into the view.

    http://trainitsolutions.com/2014/10/06/advantages-of-viewmodel-in-mvcmodel-view-controller-2/

    https://www.tutlane.com/tutorial/aspnet-mvc/how-to-use-viewmodel-in-asp-net-mvc-with-example

    Friday, February 15, 2019 5:08 AM