Try our conversational search powered by Generative AI!

how to retrieve categories on view page?


In CMS 12, how to retrieve categories in CMS 12. 

When I use this existing code:

 var categoryRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<CategoryRepository>();
 var filterBlock = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<FilterBlock>();

It's causing errors..please advise.


Jan 11, 2023 8:09

What is the error you are facing, I have just tried inside the View for an Article Page on the Alloy Templates and all seems to work 

Jan 12, 2023 14:36

I realized the problem was not in the code with categoryRepository but the next line of code:

 var filterBlock = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<FilterBlock>();

This was causing this error: 

Exception thrown: 'System.InvalidOperationException' in Microsoft.Extensions.DependencyInjection.Abstractions.dll

I have removed this in code, and it works fine, but what is the substitute for that in .NET Core


Jan 12, 2023 16:10

Im not sure if you are in a view or the block itself 

If you are trying to get the Content Type of a particular Block and know its ContentId I would use IContentRepository 


this.contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
// Could cause null reference exception so might be worth going down the .TryGet route 
var filterBlock= contentRepository.Get<FilterBlock>(x.ContentLink);

Jan 13, 2023 0:48
* 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.