Copied to clipboard

Flag this post as spam?

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


  • tom8825 3 posts 23 karma points
    May 16, 2021 @ 13:02
    tom8825
    0

    Why cant i access these child node fields in razor?

    I have used the lines below to get the child resort node of my home page.

    var children = Model.Children().ToList();
    List<IPublishedContent> resorts = children.Where(x => x.Name == "Resorts").ToList().FirstOrDefault().Children().ToList();
    

    im using a foreach to iterate through the resorts and display the bodyText content. I can see the content is retrived when debugging, but i cannot display it with 'resort.BodyText'. Default fields like Name and Id work fine though.

    enter image description here

  • Marc Goodson 2148 posts 14352 karma points MVP 8x c-trib
    May 16, 2021 @ 15:31
    Marc Goodson
    1

    Hi tom8825

    The .Children property (and other collections of related items to the current item) return objects as implementation of IPublishedContent which is the general representation of content items in Umbraco, and all items have an Id and a Name, which is why you can read those properties directly...

    ... but different types of pages might have different properties, and so the Children helper doesn't know which type of page happens to be created underneath the current page...

    So you can either user the .Value helper to read the value from the IPublishedContent item eg

    @foreach (resort in resorts){
    <h2>@resort.Value("resortName")</h2>
    @resort.Value("bodyText")
    }
    

    of if you are keen to stick with the generated models approach and you know your Children of this node will be of the same type you can tell Umbraco that using the .OfType<YourModel>() extension

    eg

    @{
        var children = Model.Children().ToList();
        List<IPublishedContent> resorts = children.Where(x => x.Name == "Resorts").ToList().FirstOrDefault().Children().OfType<ResortPage>().ToList();
    }
        @foreach (resort in resorts){
        <h2>@resort.ResortName</h2>
        @resort.BodyText
        }
    

    guessing what the name of your model is for a resort and what properties it might have!

    But that does give you a steer as to what is going on, and what you can do handle the children in a strongly typed way?

    regards

    marc

Please Sign in or register to post replies

Write your reply to:

Draft