Created
July 25, 2017 12:29
-
-
Save tim-elvidge/672d29e120853cc7c361551147098f5b to your computer and use it in GitHub Desktop.
This file contains 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.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