ASP.Net Core - Render a View to a String

Posted by Blake on 5/10/2018
)

Here is an ASP.Net core extension method built off of the Controller class that will allow you to render a View to a string. I've used this in a number of places such as templating HTML for emails where the content needed to be generated with advanced logic or when I've needed to store the exact contents of what was rendered from a View.

C#


    /// <summary>
    /// Renders a View to a string.
    /// </summary>
    /// <param name="controller">The current controller.</param>
    /// <param name="serviceProvider">The service provider required to get a composition engine.</param>
    /// <param name="viewName">The name of the view that should be loaded.</param>
    /// <param name="model">The object model that should be passed to the view.</param>
    /// <returns></returns>
    public static string RenderViewToString(this Controller controller, IServiceProvider serviceProvider, string viewName, object model)
    {
        controller.ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            var engine = serviceProvider.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
            ViewEngineResult viewResult = engine.FindView(controller.ControllerContext, viewName, false);

            ViewContext viewContext = new ViewContext(
                controller.ControllerContext,
                viewResult.View,
                controller.ViewData,
                controller.TempData,
                sw,
                new HtmlHelperOptions() //Added this parameter in
            );

            var t = viewResult.View.RenderAsync(viewContext);
            t.Wait();

            return sw.GetStringBuilder().ToString();
        }
    }