Monday, April 16, 2018

How to render ASP.NET views in the backend

Did you know that we have an elegant approach to generate views with ASP.NET and ASP.NET Core? Read to understand.

It's possible that your backend runs on a different server than your web server. What would you do if you have to render certain views or even send emails on your backend (ex. reset password token) but don't have access to the MVC framework from it?


An elegant solution would be using RazorTemplates. RazorTemplates is an open source templating engine based on Microsoft's Razor parsing engine. The library allows building razor templates outside ASP.NET MVC Projects including in our own backends. It solves that common use case where we need to email users from our backends.

For reference, the github page is located here.

Using RazorTemplates

Add a reference to your project

The first thing you need to do is to add a reference to the RazorTemplates nuget package to your solution:
Project -> Manage Nuget Packages -> search for "RazorTemplates":

Create your view

Once added, it's time to create your views. Simply create a csthml in your non-web project as you would create any other file type, suffixing it with cshtml.

Note that here my model is dynamic so I'm not required to have a strongly typed model.

Set the custom tool property

Because you want to use your view server side, you need to have a C# file to reference it. To make that happen, you need to configure Visual Studio to to scaffold the C# code for you. To do so: click on your recently added file and press F4 to display the Properties Window, then set the custom tool property to "RazorGenerator":

Render the view in the backend using C#

Then, to have your template generated, you just need to call RazorTemplate's TransformText method. After the above code is run, TransformText returns you a string with the rendered content. You can then email that string or create fancy reports from your backend.

RazorTemplates and ASP.NET Core

To Asp.Net core users, Microsoft just released a similar approach to Razor UI in class libraries. We will explore that feature in the blog in the future.

Final Thoughts

While ASP.NET Core provides server-side view generation, none exists for ASP.NET. Since one of the most common scenarios developers encounter is emailing users from the backend, an elegant solution would be using the aforementioned RazorTemplates nuget package.

See Also

About the Author

Bruno Hildenbrand      
Principal Architect, HildenCo Solutions.