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.

icon of user profile

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

 
//inside a web api call or what ever
CategoryDataModel currentContent = _urlResolver.Route(new UrlBuilder(Request.Headers.Referrer?.AbsolutePath)) as CategoryDataModel; //CategoryDataModel is Episerver CatalogNode 
if (currentContent != null && currentContent.BlockContentInProductList != null && currentContent.BlockContentInProductList.FilteredItems.Any())
{
      //ContentRendererService from Constructor
      IEnumerable listOfRenderedContent = _contentRendererService.RenderContentToHtml(currentContent.BlockContentInProductList.FilteredItems)?.ToArray();
       return listOfRenderedContent;
}

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

Render a ContentReference with a specific tag

//ContentRendererService from Constructor
_contentRenderService.Render(contentReference, tags: new string[1] { "sometag" }); // or tags: null if default view

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