Monday, April 16, 2018

Asp.Net / Asp.Net Core: Generating views in the backend

It's possible that your backend runs on a different server than your web server. The problem is that sometimes you have to render certain views or even send emails from your backend (ex. reset password token) but you don't have access to the MVC framework (System.Web.Mvc). How do you solve it?

In Asp.Net, a solution to that would be using the RazorTemplate nuget package. Let's take a look.

RazorTemplates

RazorTemplates is an open source templating engine based on Microsoft's Razor parsing engine. Thread safe. Allows running Razor templates outside ASP.Net MVC Projects. 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.

Keep tuned!

See Also

Why you should start using .Net Core
Package Management in .Net Core
Exporting Html to Pdf using only JavaScript
Importing CSVs with .Net Core and C#
Exporting a CSV generated in-memory in Asp.Net with C#
Building and Running Asp.Net Core apps on Linux
Testing Javascript on Asp.Net Core Applications