Don't miss out Virtual Happy Hour this Friday (April 26).

Try our conversational search powered by Generative AI!

How to get type of first item in ContentArea?

Vote:
 

I need to get the type of the block that is inserted in a ContentArea, to determine how the html should be rendered. Is there a simple way to get this? It seems to me that the only type I can find is the ContentAreaItem, which is the same for all items in the area. If I drop a block of type ProductsBlock, I would like to get that in my view so I know if the block should be treated in a different way or not. How can I get the type?

#171940
Nov 22, 2016 9:55
Vote:
 

Hi Alfred,

You need to fetch the block by using the content link from the ContentAreaItem. Then you can check if the block is a ProductsBlock.

e.g.

var firstContentAreaItem = myContentArea.FilteredItems.FirstOrDefault();

var myBlock = contentRepository.Get<BlockData>(firstContentAreaItem .ContentLink);

if (myBlock is ProductsBlock)

{

...

}
#171942
Nov 22, 2016 10:11
Vote:
 

Thanks! How do I access the contentRepository?

#171943
Nov 22, 2016 10:45
Vote:
 

You need to get an instance to IContentRepository.  You can do that by initializing it in your class' constructor.

Or

var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();

Then you can: 

var myBlock = contentRepository.Service.Get<BlockData>(firstContentAreaItem .ContentLink);



#171944
Nov 22, 2016 10:55
Vote:
 

How do I reference the IContentRepository? I can't understand where it is, should I add a @using something to include it?

#171945
Nov 22, 2016 11:08
Vote:
 

using EPiServer;

#171946
Nov 22, 2016 11:14
Vote:
 

@Alfred

IContentRepository is EPiServer built-in interface under EPiServer namespace. You need to either add using statement or using fully qualified name EPiServer.IContentRepository. 

See EPi documentation here

During the project start, epi will register the implementation of this interface in structuremap container, therefore you can easily pass this interface into your class via the constructor injection if you are comfortable with IOC and DI. Alternatively, Epi provides a ServiceLocator helper class that can help you to get the instance as well. 

ServiceLocator Helper documentation

There is no way you can new up concrete implementation of IContentRepository in EPiServer. That's one of the OOP recommendation - "Programming to interfaces, not implementations"

#171988
Nov 23, 2016 2:08
* 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.