Copied to clipboard

Flag this post as spam?

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


  • Beginner 28 posts 78 karma points
    Jul 09, 2015 @ 12:28
    Beginner
    0

    Problems with foreach in image slider

    I have some issues with my foreach and I want to create an image slider. On my “home” page I want to use a slider(se images) I have a doctype in the root(alias=ImageSlider) named slider2. Then I have a doctype (alias=Image) which contains 2 inputfields and an image. My foreach looks like this in my partial file:

    @foreach (var slide in CurrentPage.Children){
    <div>
            <h2>@slide.imgHeader</h2>
            <p>@slide.imageText</p>
    
            @if (slide.ImageForSlide != null && !(slide.ImageForSlide is Umbraco.Core.Dynamics.DynamicNull))
            {
                var m = Umbraco.Media(slide.ImageForSlide);
                <img src="@m.Url" alt="@m.UrlName" />
            }
    </div>}
    

    I do not get any output from this. enter image description here

    Is it possible to do it like this??

    Hope someone can help me :)

  • Dennis Aaen 4500 posts 18255 karma points admin hq c-trib
    Jul 10, 2015 @ 08:22
    Dennis Aaen
    0

    Hi Beginner,

    I think something like this will work for you

    @{
        var imageSlider = Umbraco.ContentAtRoot().DescendantsOrSelf("ImageSlider").FirstOrDefault();
    
        foreach(var slide in imageSlider.Children.Where("Visible")){ 
            <div>
                @if(slide.HasValue("imgHeader") || slide.HasValue("imageText")){ 
    
                    <h2>@slide.imgHeader</h2>
                    <p>@slide.imageText</p>
                }
    
    
                <img src="@item.umbracoFile" alt="@item.Name" />
    
            </div>
        }
    }
    

    Hope this helps,

    /Dennis

  • Lex Godthelp 24 posts 106 karma points
    Jul 10, 2015 @ 14:02
    Lex Godthelp
    0

    Hi beginner,

    I would start with defining a selection instead of using CurrentPage.Children if you dont get any results:

    var selection = CurrentPage.Site().FirstChild("ImageSlider").Children("Image").Where("Visible");
    

    Then use this selection in a foreach:

    @foreach(var item in selection){
        <div>
            <h2>@slide.imgHeader</h2>
                <p>@slide.imageText</p>
        </div>
    }
    

    It might be you need to use @slide.GetPropertyValue("imgHeader") instead of @slide.imgHeader.

    You can use slide.HasValue("ImageForSlide") to check if that specific field has a value like Dennis suggested. I'm trying to help out to improve my own Razor skills, so let me know what works for you.

    *Lex

Please Sign in or register to post replies

Write your reply to:

Draft