ASP.Net Core - Render a View to a String

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.


/// <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>
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(
            new HtmlHelperOptions() //Added this parameter in

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

        return sw.GetStringBuilder().ToString();

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.