Get category names from category list in view/cshtml?

Vote:
 

In my view/cshtml file I want to extract the category names in a block.

var categoryCurrentBlock = (ICategorizable)currentBlock;

I use the above to get a list of categories in my block. How do I access the names of the categories? To use in my view

#266923
Nov 18, 2021 6:22
Vote:
 

Inject the CategoryRepository and you can get the Category class by the id of the item stored in the CategoryList on the block.

#266924
Nov 18, 2021 9:12
Scott Reed - Nov 18, 2021 9:27
Plus I'd recommend against doing these in a view. Ideally for separation of logic and the view these should be done in a controller and passed in to a viewmodel to the view.
kingofeverything131 - Nov 18, 2021 17:38
Do you have a sample code on how to use CategoryRepository?
Scott Reed - Nov 18, 2021 18:15
- Category on the block is s CategoryList which is a list of IDs.
- Inject instance of CategoryRepository
- Call the get method on the CategoryRepository instance passing in one of the IDs from the CategoryList

It's fairly straight forward. https://world.optimizely.com/csclasslibraries/cms/EPiServer.DataAbstraction.CategoryRepository?version=8
kingofeverything131 - Nov 18, 2021 22:12
But what do you mean by “inject instance”?
Scott Reed - Nov 19, 2021 9:06
If you're not sure what dependency injection is I'd google it and have a read. It's a core part of modern application design within the .NET and C# platform. Optimizely is built from the ground up to be able to inject dependencies (usually by constructor) so you NEED to understand it to work with the platform.

Read this after you've read about DI in .NET https://world.optimizely.com/documentation/developer-guides/CMS/initialization/dependency-injection/
Scott Reed - Nov 19, 2021 9:10
However as mentioned you should be doing this in a Controller or services run within a controller. The standard way is to inject the instance in the constructor of your controller for your block as you can't inject things in views as they are just for presentation. You can use the ServiceLocator with code such as ServiceLocator.Current.GetInstance however it's an anti pattern and shouldn't be used in a view
* 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.