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?
You need to fetch the block by using the content link from the ContentAreaItem. Then you can check if the block is a ProductsBlock.
var firstContentAreaItem = myContentArea.FilteredItems.FirstOrDefault();
var myBlock = contentRepository.Get<BlockData>(firstContentAreaItem .ContentLink);
if (myBlock is ProductsBlock)
Thanks! How do I access the contentRepository?
You need to get an instance to IContentRepository. You can do that by initializing it in your class' constructor.
var contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
Then you can:
var myBlock = contentRepository.Service.Get<BlockData>(firstContentAreaItem .ContentLink);
How do I reference the IContentRepository? I can't understand where it is, should I add a @using something to include it?
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"