In this post, you will learn how to bypass normal Episerver routing and manually get the action/controller used within a request for a block. This technique is very different than how you would normally hook into a controller using a page or a block. In most instances when you may need to think about custom routing it is usually when you are trying to create a custom form. More information about this can be found in, Creating an Episerver Sign-Up Form.

Template Resolver

In Episerver, blocks and block partials are rendered using the template resolver

The template resolver can be overridden and if you want to render your blocks with display options or without a controller, then this is something that you may look into, How To Make A Block Use Multiple Views? A Partial View Controller Explained. The code below is assuming you're either in a custom MVC Html helper, or you are overriding the ContentAreaRendere.

The code uses two Episerver API's. The template resolver, this will figure out the controller name for a block for us and the content type repository. This API will get a blocks content type Id, look it up in the database and return the matching Episerver object. The first thing we do is get the content type from the content item being passed in, using the ContentTypeID property.

The next thing is querying the template recover.  In my snippet, I've included three ways that will all return the values you want.  The best approach is to use ResolveMvcTemplate as it saves you specifying the template type category. From the object that's returned, you can then do recommendOption.Name to get the controller name!

Conclusion

Getting the controller name from a block is a bit of a faff and uses a few API'd that aren't really documented very well. The code to actually get the name is pretty simple and straightforward, we grab an instance of the block, pass it to the template resolver with the correct parameters and then use the Name property to get the controller name.