Skip to content

Instantly share code, notes, and snippets.

@StrutTower
Created May 27, 2019 01:35
Show Gist options
  • Save StrutTower/da303d31f2c930cb5a34af7a0968a0d3 to your computer and use it in GitHub Desktop.
Save StrutTower/da303d31f2c930cb5a34af7a0968a0d3 to your computer and use it in GitHub Desktop.
ASP Core 2 Render a View to a String
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.IO;
using System.Threading.Tasks;
namespace Website.Infrastructure {
public class CustomController : Controller {
public async Task<string> RenderViewAsync<TModel>(string viewName, TModel model, bool partial = false) {
if (string.IsNullOrEmpty(viewName)) {
viewName = ControllerContext.ActionDescriptor.ActionName;
}
ViewData.Model = model;
using (var writer = new StringWriter()) {
IViewEngine viewEngine = HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
ViewEngineResult viewResult = viewEngine.FindView(ControllerContext, viewName, !partial);
if (viewResult.Success == false) {
return $"A view with the name {viewName} could not be found";
}
ViewContext viewContext = new ViewContext(
ControllerContext,
viewResult.View,
ViewData,
TempData,
writer,
new HtmlHelperOptions()
);
await viewResult.View.RenderAsync(viewContext);
return writer.GetStringBuilder().ToString();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment