Last active
November 26, 2018 23:42
-
-
Save Torvin/d06766c6195e1dba63d1c3a63a6e3e0c to your computer and use it in GitHub Desktop.
Render a Razor view in ASP.NET Core 2.1. The view name should be in "~/path/to/view.cshtml" form
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.AspNetCore.Mvc.ModelBinding; | |
using Microsoft.AspNetCore.Mvc.Rendering; | |
using Microsoft.AspNetCore.Mvc.ViewEngines; | |
using Microsoft.AspNetCore.Mvc.ViewFeatures; | |
public class RazorViewRenderer | |
{ | |
private readonly ICompositeViewEngine _viewEngine; | |
private readonly IServiceProvider _serviceProvider; | |
public RazorViewRenderer(ICompositeViewEngine viewEngine, IServiceProvider serviceProvider) | |
{ | |
_viewEngine = viewEngine; | |
_serviceProvider = serviceProvider; | |
} | |
public async Task<string> RenderView(string viewName, object model, IDictionary<string, object> viewData = null) | |
{ | |
var viewResult = _viewEngine.GetView(null, viewName, false); | |
if (!viewResult.Success) | |
throw new Exception("View not found."); | |
var data = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }; | |
if (viewData != null) | |
{ | |
foreach (var (key, value) in viewData) | |
data.Add(key, value); | |
} | |
using (var sw = new System.IO.StringWriter()) | |
{ | |
var viewContext = new ViewContext | |
{ | |
HttpContext = new DefaultHttpContext { RequestServices = _serviceProvider }, | |
View = viewResult.View, | |
ViewData = data, | |
Writer = sw, | |
}; | |
await viewResult.View.RenderAsync(viewContext); | |
return sw.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment