Using Razor for HTML templating has never been easier. Render your .cshtml files to strings easily using this library.
This library uses precompiled Razor views provided by the Razor SDK.
| .NET 6 & Above | .NET 10 & Above | |
|---|---|---|
| Preferred Version | v2.1.0 | 3.0.0 |
| Console | âś“ | âś“ |
| Api | âś“ | âś“ |
| Mvc | âś“ | âś“ |
| Worker Service | âś“ | âś“ |
| WPF | âś“ | âś“ |
| WinForms | âś“ | âś“ |
| Azure Functions | âś“ | âś“ |
For older .NET versions, refer to the wiki
| MVC Razor View Features | |
|---|---|
| ViewModel | âś“ |
| ViewBag | âś“ |
| ViewData | âś“ |
| Layouts | âś“ |
| ViewStarts | âś“ |
| ViewImports | âś“ |
| Partial Views | âś“ |
| Tag Helpers | âś“ |
| View Components | âś“ |
| View Localization (Only MVC) | âś“ |
| Dependency Injection into Views | âś“ |
| @Url.ContentUrl** | âś— |
| @Url.RouteUrl** | âś— |
**Contributors are welcome who can help to enable these unsupported features.
- Email Templating
- Report Generation & more
Performance of rendering the views to HTML is as fast as rendering the MVC page. The first render may be slightly slower due to the initialization. But, the subsequent renderings are significantly faster. Refer to the benchmark results here and run it for yourself in your own machine to verify the results.
| Method | Mean | Error | StdDev | Gen0 | Allocated |
|---|---|---|---|---|---|
| RenderViewWithModelAsync | 28.73 ÎĽs | 0.403 ÎĽs | 0.357 ÎĽs | 5.8594 | 24 KB |
From .NET 10, the Razor runtime compilation APIs are marked as obsolete. As a result, they will be removed from ASP.NET Core in the future. If you're looking to save a Razor view in a database or in a separate folder outside the project and render it on the fly, that scenario is not supported. Microsoft recommends using build-time compilation by including the Razor view in the project and built as part of your app.
This library is available as NuGet package
dotnet add package Razor.Templating.Core<PackageReference Include="Razor.Templating.Core" Version="3.0.0" />To render a view with a layout, model, ViewData, or ViewBag, call RenderAsync() on the RazorTemplateEngine static class.
using Razor.Templating.Core;
var model = new ExampleModel()
{
PlainText = "This text is rendered from Razor Views using Razor.Templating.Core",
HtmlContent = "<em>You can use it to generate email content, report generation and so on</em>"
};
// Both ViewBag and ViewData should be added to the same dictionary.
var viewDataOrViewBag = new Dictionary<string, object>();
// ViewData is the same as in MVC.
viewDataOrViewBag["Value1"] = "1";
// ViewBag.Value2 can be written as shown below. There's no change in how it's accessed in a .cshtml file.
viewDataOrViewBag["Value2"] = "2";
var html = await RazorTemplateEngine.RenderAsync("/Views/ExampleView.cshtml", model, viewDataOrViewBag);Before using this code, see this article for a sample implementation: https://medium.com/@soundaranbu/render-razor-view-cshtml-to-string-in-net-core-7d125f32c79
If you need to render a view without a layout, use the RenderPartialAsync() method.
var html = await RazorTemplateEngine.RenderPartialAsync("/Views/ExampleView.cshtml", model, viewDataOrViewBag);There are TryRenderAsync() and TryRenderPartialAsync() methods which do not throw an exception if the view doesn't exist. Instead, they return a tuple indicating whether the view exists and the rendered string.
var (viewExists, renderedView) = await engine.TryRenderAsync("~/Views/Feature/ExampleViewWithoutViewModel.cshtml");var (viewExists, renderedView) = await engine.TryRenderPartialAsync("~/Views/_ExamplePartialView.cshtml", model);You can organize Razor view files (.cshtml) in a separate shared Razor Class Library (RCL). See a sample library here.
The Razor Class Library's .csproj file should look like the example below. The AddRazorSupportForMvc property is required.
Also, the RCL should be referenced by the main project or by any project that invokes rendering methods such as RazorTemplateEngine.RenderAsync().
<Project Sdk="Microsoft.NET.Sdk.Razor">
<PropertyGroup>
<TargetFrameworks>net6.0</TargetFrameworks>
<AddRazorSupportForMvc>true</AddRazorSupportForMvc>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>Dependencies can be injected directly into views using @inject in a .cshtml file. See a sample application here
In ASP.NET Core, register dependencies as shown below in Program.cs
...
builder.Services.AddTransient<ExampleService>();
// Add this after registering all other dependencies
builder.Services.AddRazorTemplating();or in console or other applications, add as below
using Microsoft.Extensions.DependencyInjection;
// Add dependencies to the service collection
var services = new ServiceCollection();
services.AddTransient<ExampleService>();
// Add RazorTemplating after registering all dependencies
// This is important for the Razor template engine to find injected services.
services.AddRazorTemplating(); Once the dependencies are registered, we can use either one of these ways:
var html = await RazorTemplateEngine.RenderAsync("~/Views/ExampleViewServiceInjection.cshtml");- Instead of using the
RazorTemplateEnginestatic class, you can use theIRazorTemplateEngineinterface and inject it directly into your class constructor.
public class MyService {
private readonly IRazorTemplateEngine _razorTemplateEngine;
public MyService (IRazorTemplateEngine razorTemplateEngine)
{
_razorTemplateEngine = razorTemplateEngine;
}
public async Task Index()
{
var renderedView = await _razorTemplateEngine.RenderAsync("/Views/Home/Index.cshtml");
// do something with renderedView
}
}- Please ensure that view paths are unique across all shared template projects.
Please find the sample applications here
If you find this helpful, consider supporting development by buying a coffee. Thanks!
Thanks to all the great articles and projects that helped bring this library to life!
- https://github.com/Andy9FromSpace/razor-renderer-core
- https://github.com/aspnet/Entropy/tree/master/samples/Mvc.RenderViewToString
- https://www.frakkingsweet.com/razor-template-rendering/
- https://github.com/veccsolutions/RenderRazorConsole
- https://emilol.com/razor-mailer/
- https://codeopinion.com/using-razor-in-a-console-application/