Over 10 years we help companies reach their financial and branding goals. Engitech is a values-driven technology agency dedicated.

Gallery

Contacts

411 University St, Seattle, USA

+1 -800-456-478-23

Development

Rendering razor views that contain helpers with RazorEngine

The problem

I recently was working on a codebase that was using .NET 4.7.2, where we began porting a portion of the codebase that was sitting in MVC controllers to API controllers. A part of the code that we were porting included rendering razor views. Since the code I mentioned was sitting in MVC views, rendering razor views was done by built-in MVC mechanism.

Of course, when I started porting the code that was rendering the razor views, I no longer had access to those MVC goodies, so I basically had to rewrite how the razor views are rendered by making sure the end result stays the same.

After doing a bit of research, I decided the easiest way to emulate the same result would be by utilizing RazorEngine.

Rendering the view with RazorEngine was straightforward enough. All I had to was to read the view into a string variable and call RazorEngine’s RunCompile method.

After doing all that however, I got hit with the following errors:

- error: (853, 30) The name ‘Html’ does not exist in the current context
- error: (871, 52) The name 'Json' does not exist in the current context

Checking out the template I was trying to render, I saw the template was using Html.Raw and Json.Encode.

The solution

Luckily, the solution to the problem I was facing was straightforward enough.

Here are the three classes that were necessary in order for RazorEngine to start compiling templates that contained Html.Raw and Json.Encode:

public class HtmlHelpers
{
    public IEncodedString Raw(string rawString)
    {
        return new RawString(rawString);
    }
}

public class JsonHelpers
{
    public string Encode(object value)
    {
        return Json.Encode(value);
    }
}

public abstract class HtmlSupportTemplateBase<T> : TemplateBase<T>
{
    public HtmlHelpers Html { get; set; } = new HtmlHelpers();

    public JsonHelpers Json { get; set; } = new JsonHelpers();
}

And here’s how we create the IRazorEngineService that utilizes HtmlSupportTemplateBase<T>:

var config = new TemplateServiceConfiguration
{
    BaseTemplateType = typeof(HtmlSupportTemplateBase<>)
};

using (var service = RazorEngineService.Create(config))
{
    // Call RunCompile here using the template and view model
}

And that’s pretty much it. Now that we told RazorEngine what Html.Raw and Json.Encode are supposed to do, it’s able to compile the template just fine.

This goes without saying, but this can be extended to anything else that you have in your template.

Thank you for reading and I hope this saves you a bit of time if you’ve encoutnered the same problem that I have.

Author

Kerim Emurla

Leave a comment

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