Render ContentArea and Content Views to string

How to render pages, blocks, media and other in a custom content rendering out of the MVC context pipeline.

Published 31th of October 2020
Epi CMS version 11.14

I had the need to render the content from a content area and deliver it to react front end thru a web api.

Seemed not so hard, in theory, google a little, found some, like this blog post from EMVP colleague Casper Rasmussen http://fellow.aagaardrasmussen.dk/2016/11/01/how-to-render-an-episerver-contentreference-via-your-webapi/

I evolved his code a little bit, since I had blocks without controllers, I had to take care of that by adding a fake custom controll if the controller was missing, and it also seemed that Episerver had changed some stuff under the hood, like “contextmode” see code routeData.DataTokens[“contextmode”] //important to declare that the rendering should NOT be “edit”-mode when runing the web api / page in edit mode.

I also wanted to render ContentArea with use of display options, so I added LoadDisplayOptions and used tags feature when rendering.

Result: success!

Example usage

Content Renderer on a page ContentArea

The greatness with this is the renderer loading the DisplayOptions and uses the tag feature in Episerver

Render a ContentReference with a specific tag

Result

Renders a string with the executed cshtml

The Code

Copy and paste this into a new class, and your good to go:

The custom code content: Class ContentRendererService, FakeView, Fake CustomController.

About the author

Luc Gosso
– Independent Senior Web Developer
working with Azure and Episerver

Twitter: @LucGosso
LinkedIn: linkedin.com/in/luc-gosso/
Github: github.com/lucgosso

Like it? please up vote
1

Leave a Reply

Your email address will not be published. Required fields are marked *