Copied to clipboard

Flag this post as spam?

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


  • Mike 62 posts 274 karma points
    Mar 14, 2013 @ 01:03
    Mike
    0

    Displaying parent nodes in Razor menu when no child nodes exist

    Hey all,

    I feel this is a simple task, however, I'm battling to get my head around this. I have a sub-menu which I'm converting from XSLT to Razor. The code simply lists any child nodes that exist under the parent.

    @inherits umbraco.MacroEngines.DynamicNodeContext

    <ul>
        @foreach (var item in @Model.Children.Where("Visible"))
        {
            <li><a href="@item.Url">@item.Name</a></li>
        }
    </ul>

    What I'm trying to do is adjust the code so that when no child exists under a node the parent nodes persist so, in effect, the sub-menu doesn't disappear.

    Could anyone provide any code pointers please?

    Many thanks,
    Mike

  • Fuji Kusaka 2203 posts 4220 karma points
    Mar 14, 2013 @ 08:41
    Fuji Kusaka
    100

    Hi Mike

    Try doing something like

    @if(@Model.Children.Where("Visible").Count() > 0) {
    //// either make your loop or display parent name 
    }

    Is this what you are trying to achieve here ?

    //fuji

  • Mike 62 posts 274 karma points
    Mar 14, 2013 @ 17:08
    Mike
    0

    Hi Fuji,

    Yeah this is definitely along the right sort of lines. So this is what I've written. It works but I'm not sure it is the best way of writing it:

    @inherits umbraco.MacroEngines.DynamicNodeContext
        @{
            var currentPage = Model;

            <ul>
                @foreach (var item in currentPage.Children.Where("Visible"))
                {
                    <li><a href="@item.Url">@item.Name</a></li>
                }

                @if(currentPage.Children.Where("Visible").Count() == 0) {
                    foreach (var item in currentPage.Parent().Children.Where("Visible")) {
                        <li><a href="@item.Url">@item.Name</a></li>
                    }
                }
            </ul>
        }

    So basically the menu shows any child links that are available and visible until it can't find any more children, at this point the menu should show and persist a list of the children at its parent level - i.e. the menu doesn't just disappear off the screen.

    Is there a more efficient way of writing the above? Like I say, it works but is it the best way?

    Many thanks,
    Mike

     

Please Sign in or register to post replies

Write your reply to:

Draft