Last Updated: February 25, 2016
·
1.157K
· ridermansb

Render view as string

public static string RenderViewAsString(this Controller controller, ControllerContext context, string viewName, object model)
{
    var stringWriter = new StringWriter();
    var viewResult = ViewEngines.Engines.FindView(context, viewName, null);
    var viewContext = new ViewContext(
            controller.ControllerContext,
            viewResult.View,
            new ViewDataDictionary(model),
            controller.TempData,
            stringWriter
            );

    viewResult.View.Render(viewContext, stringWriter);
    return stringWriter.ToString();
}

When you use within an API controller, you have a problem with the ControllerContext :)

Here's a tip from Wouter de Kort (http://wouterdekort.blogspot.com.br/2012/10/rendering-aspnet-mvc-view-to-string-in.html?showComment=1363116520203#c637135064697708476(