In this post, you will learn how to get the default action method and controller for an Episerver block in code. This technique is very different compared to how you would normally call a block in Episerver CMS. Normally, you would define a ContentArea property on a page and using PropertyFor() let Episerver do all the routing for you. Unless you have a good reason to do something different, this is the technique you should use normally.

When building some sites, you may encounter a requirement that means you need to access a block differently. You may find yourself in some area of code, where you need to manually trigger the Episerver routing. Maybe you want to create a vanilla MVC controller and call a block. If you find yourself in this situation, this is this the guide for you 🔥🔥🔥

Template Resolver

In Episerver, blocks and block partials are rendered using the template resolver. The template resolver can be overridden. If you want to render your blocks with display options or without a controller, this is something that you may look into further. Read this tutorial to learn more.

In order to load a block, you can use this code:

This code uses two Episerver APIs, the IContentTypeRepository and the ITemplateResolver. The IContentTypeRepository is used to query the CMS for more information about a block. This API will find more information about a block using its ContentTypeId and the Load() method.

ITemplateResolver is used to figure out the controller name for a block. In my example, I've included three ways to return the controller name, pick the one that makes you happy 😊. My personal recommendation is to use the ResolveMvcTemplate method, as it saves you specifying the template type category. From the object that's returned, you can then use the Name property to get the controller name for the block 💥

Manually getting the controller name for a block is a bit of a faff as it uses a few APIs that aren't really documented very well. The code to actually get the name is pretty simple and straightforward. Grab an instance of the block type, pass it to the template resolver with the correct parameters and then use the Name property to get the controller name. Happy Coding 🤘