Using Razor for HTML templating was never been so easy like this. Render your .cshtml files into string easily using this library.
This project makes use of Razor SDK for precompiling the views.
.NET Core 3 to .NET 5 | .NET 6 & Above | |
---|---|---|
Preferred Version | v1.6.0 | 2.1.0 |
Console | ✓ | ✓ |
Api | ✓ | ✓ |
Mvc | ✓ | ✓ |
Worker Service | ✓ | ✓ |
WPF | ✓ | ✓ |
WinForms | ✓ | ✓ |
Azure Functions | ✓ | ✓ |
MVC Razor View Features | |
---|---|
ViewModel | ✓ |
ViewBag | ✓ |
ViewData | ✓ |
Layouts | ✓ |
ViewStarts | ✓ |
ViewImports | ✓ |
Partial Views | ✓ |
Tag Helpers | ✓ |
View Components (.NET 5 +) | ✓ |
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
This library is available as Nuget package
dotnet add package Razor.Templating.Core
<PackageReference Include="Razor.Templating.Core" Version="2.1.0" />
To render a view with layout, model, viewdata or viewbag, then call the 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 same as mvc
viewDataOrViewBag["Value1"] = "1";
// ViewBag.Value2 can be written as below. There's no change on how it's accessed in .cshtml file
viewDataOrViewBag["Value2"] = "2";
var html = await RazorTemplateEngine.RenderAsync("/Views/ExampleView.cshtml", model, viewDataOrViewBag);
Before applying this code, follow this article for sample implementation: https://medium.com/@soundaranbu/render-razor-view-cshtml-to-string-in-net-core-7d125f32c79
In case if there's a need to render a view without layout, use RenderParitalAsync()
method.
var html = await RazorTemplateEngine.RenderPartialAsync("/Views/ExampleView.cshtml", model, viewDataOrViewBag);
There are TryRenderAsync()
and TryRenderPartialAsync
methods which will not throw exception if the view doesn't exist.
Instead they return a tuple to indicate 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);
We can organize the Razor view files(.cshtml) in a separate shared Razor Class Libary(RCL). Please find a sample library here
The Razor Class Library's .csproj
file should look something like below. Whereas, AddRazorSupportForMvc
property is mandatory.
Also, RCL should be referenced by the main project or where any of the rendering methods like RazorTemplateEngine.RenderAsync()
are invoked.
<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 .csthml file. Refer sample application here
In ASP.NET Core, add dependency like below in Startup.cs -> ConfigureServices
...
services.AddTransient<ExampleService>();
//add after registering all the dependencies
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 the 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
RazorTemplateEngine
static class, it's also possible to use theIRazorTemplateEngine
interface to inject dependency directly into the 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
}
}
We can make use of ASP.NET Core's inbuilt RazorRuntimeCompilation to render any .cshtml inside or outside of the project.
As of v1.7.0+
, we can achieve this as below:
using Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Razor.Templating.Core;
var services = new ServiceCollection();
services.AddMvcCore().AddRazorRuntimeCompilation();
services.Configure<MvcRazorRuntimeCompilationOptions>(opts =>
{
opts.FileProviders.Add(new PhysicalFileProvider(@"D:\PathToRazorViews")); // This will be the root path
});
services.AddRazorTemplating();
var html = await RazorTemplateEngine.RenderAsync("/Views/Home/Rcl.cshtml"); // relative path to the root
Please note this may become slightly better in the future versions of our library.
- Please ensure that the views path is always unique among all the shared template projects.
Please find the sample applications here
If you find this helpful, consider supporting the development of this library by sponsoring one or more coffee ;) Thanks!
Thanks to all the great articles and projects which helped to bring this library out!
- 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/