Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 638
user3526092 Avatar asked Dec 09 '25 05:12

user3526092


2 Answers

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
}
like image 66
user2262508 Avatar answered Dec 11 '25 18:12

user2262508


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
}
like image 36
Azimuth Avatar answered Dec 11 '25 17:12

Azimuth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!