Programmatically retrieve the categories that can be assigned to pages in Episerver

user3526092 picture user3526092 · Apr 12, 2014 · Viewed 7.1k times · Source

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.

Answer

user2262508 picture user2262508 · Apr 16, 2014

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
}