Skip to content

Instantly share code, notes, and snippets.

@tim-elvidge
Created July 25, 2017 12:29
Show Gist options
  • Save tim-elvidge/672d29e120853cc7c361551147098f5b to your computer and use it in GitHub Desktop.
Save tim-elvidge/672d29e120853cc7c361551147098f5b to your computer and use it in GitHub Desktop.
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace PS.Services
{
public interface IViewRenderingService
{
Task<string> RenderViewToStringAsync(Controller controller, string viewName, object model);
}
public class ViewRenderingService : IViewRenderingService
{
private readonly ICompositeViewEngine viewEngine;
private readonly ITempDataProvider tempDataProvider;
public ViewRenderingService(ICompositeViewEngine viewEngineInject, ITempDataProvider tempDataProviderInject)
{
viewEngine = viewEngineInject;
tempDataProvider = tempDataProviderInject;
}
public async Task<string> RenderViewToStringAsync(Controller controller, string viewName, object model)
{
controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, false);
ViewContext viewContext = new ViewContext(
controller.ControllerContext,
viewResult.View,
controller.ViewData,
new TempDataDictionary(
controller.ControllerContext.HttpContext,
tempDataProvider),
sw,
new HtmlHelperOptions()
);
await viewResult.View.RenderAsync(viewContext);
return sw.GetStringBuilder().ToString();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment