Try our conversational search powered by Generative AI!

Best way to get a specific menu item and all descendants

Jon
Jon
Vote:
 

Hi,

I have a site menu structure that looks something like this –

  • Menu root
    • Sub menu 1 (MenuPage type)
    • Sub menu 2 (MenuPage type)
      • Another sub 1 (SubMenuPage type)
      • Another sub 2 (SubMenuPage type)
    • Sub menu 3

Each menu item contains a page reference to a page in the page tree.

I’m trying find the best way to retrieve the descendants for Sub menu 2.

I discovered I can get the items like so – 

var ContentModelUsage = ServiceLocator.Current.GetInstance<IContentModelUsage>();
var ContentTypeRepository = ServiceLocator.Current.GetInstance<IContentTypeRepository>();
var ContentType = ContentTypeRepository.Load<MenuPage>();
var Usages = ContentModelUsage.ListContentOfContentType(ContentType).Where(x => x.Name == "Sub menu 2");

var subMenus = _contentLoader.GetChildren<SubMenuPage>(Usages.FirstOrDefault().ContentLink).Where(x => x.Status == VersionStatus.Published && x.VisibleInMenu == true);

However, I wanted to see if there is a better way that I could find these items rather than directly querying the parent menu item by Name – as this could be changed in the CMS and then the above code would break. 

The pages where I would like to use these results would be descendants of the page referenced in Sub Menu 2 (so wondered if there was any clever way here of getting at the information).

Many thanks,
Jon.

#246533
Jan 08, 2021 10:14
Vote:
 

Hi Jon.

You can create a PageReference property on the start page and then select your menu page in it and based on that you can get the descendants of that page by this way you don't need to worry about page alteration in the future.

#246534
Jan 08, 2021 10:21
Jon
Vote:
 

Ah yes that's much better. Thanks Ravindra

#246535
Jan 08, 2021 10:32
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.