3

Does anyone have an idea of how to programmatically retrieve the categories that can be assigned to pages in Episerver? C# is the programming language that I am using but an example in VB will do as well.

user3526092
  • 63
  • 1
  • 7

3 Answers3

4

If you're after all the categories defined in the CMS, then start with fetching the root category first and all it's children.

Category rootCategory = Category.GetRoot();
CategoryCollection childCategories = rootCategory.Categories;
foreach (Category category in childCategories)
{
    // do whatever
}

If you only want to retrieve categories selected on the current page, then iterate through the Category property on the current page. It returns a CategoryList object which contains the Ids of the selected categories.

foreach (int catId in CurrentPage.Category)
{
    Category category = Category.Find(catId);
    // do whatever
}
2

Since Category.GetRoot() is marked as obsolete, this solution is more proper as per Episerver 9:

var categoryRepo = ServiceLocator.Current.GetInstance<CategoryRepository>();
var rootCategory = categoryRepo.GetRoot();
CategoryCollection childCategories = rootCategory.Categories;
foreach (Category category in childCategories)
{
// do whatever
}
Azimuth
  • 2,599
  • 4
  • 26
  • 33
0

You use the EPiServer.DataAbstraction.Category class. A good place to start would be the Category.GetRoot() method:

http://world.episerver.com/Documentation/Class-library/?documentId=cms/7/0ace72d5-11cd-b5cc-4dbe-af38a401f528

there are code examples on this page as well:

http://world.episerver.com/Documentation/Class-library/?documentId=cms/7/dbaa2f15-e227-1d1c-5142-2f245dd3e664

Andreas
  • 1,355
  • 9
  • 15