Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • ThomasBrunbjerg 86 posts 177 karma points
    Aug 21, 2017 @ 06:18
    ThomasBrunbjerg
    0

    "Index was out of range." error when setting src attribute of image on front page

    I have a carousel element on my front page, on which i want to display 3 images. I've set the src attribute of the images to this:

    @(Model.Content.GetPropertyValue<IEnumerable<IPublishedContent>>("forsideCarouselBilleder").ToList()[0].Url)
    

    With an incremented index for each image. This works fine on another page on my project, which is on the same level in my tree as my front page.

    But when i load up the front page with this code, i get this error:

    http://i.imgur.com/UzwElyt.png

    I don't understand why I am getting this error. All my templates has a single master template. I'm also not sure what index parameter the error is referring to.

  • Marc Goodson 617 posts 3810 karma points MVP 3x c-trib
    Aug 21, 2017 @ 07:50
    Marc Goodson
    0

    I think for some reason one of your forsideCarouselBilleder carousel images is null and so when you retrieve your items there is nothing in the list when you call ToList() and so when you use [0] to read the first indexed item in the List, you are getting the error message that the index is out of range!

    I would probably consider breaking down the access to the Url into steps, as this gives you a clearer idea for debugging, just where it is going wrong, eg:

    @{
    var carouselImages = Model.Content.GetPropertyValue<IEnumerable<IPublishedContent>>("forsideCarouselBilleder").Where(f=>f!=null);
    
    //first or default will retrieve the first item in a list/enumerable or null if there is not one there
    var carouselImage = carouselImages.FirstOrDefault();
    
    }
    //then you can safely write out the image tag if the image exists
    @if(carouselImage != null){
    <img src="@carouselImage.Url" />
    }
    

    regards

    Marc

  • ThomasBrunbjerg 86 posts 177 karma points
    Aug 21, 2017 @ 08:20
    ThomasBrunbjerg
    0

    I'm getting a different error now.

    "CS0019: Operator '>' cannot be applied to operands of type 'method group' and 'System.Collections.Generic.IEnumerable

    At this line:

    var carouselImages = Model.Content.GetPropertyValue>("forsideBilleder").Where(f=>f!=null);
    

    Am I missing some references?

    Edit: Nevermind, I fixed it :)

  • Marc Goodson 617 posts 3810 karma points MVP 3x c-trib
    Aug 21, 2017 @ 10:11
    Marc Goodson
    0

    Typo! :-P

Please Sign in or register to post replies

Write your reply to:

Draft