dcsimg
Results 1 to 2 of 2

Thread: Cannot apply index with [ ] to an expression of type icollection MVC view ASP.NET cor

  1. #1

    Thread Starter
    Member
    Join Date
    Apr 2018
    Posts
    60

    Cannot apply index with [ ] to an expression of type icollection MVC view ASP.NET cor

    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 ?

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    102,586

    Re: Cannot apply index with [ ] to an expression of type icollection MVC view ASP.NET

    Quote Originally Posted by engbarbary View Post
    How to convert collection to list
    There's no need.
    Quote Originally Posted by engbarbary View Post
    How using indexing in collection ?
    You can't.

    The solution is to use a 'foreach' loop rather than a 'for' loop. You should do the same even if the property was an IList<T>. If the point of your loop is to access each item in a collection, use a 'foreach' loop because that is exactly what it does. Use a 'for' loop only if you need to use the loop counter for something other than indexing the collection, e.g. indexing two concurrent collections.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width