How to Render an ASP.NET MVC View to a String From Within the Controller

When using AJAX in a site I often find myself needing to pass a significant portion of HTML back to the client along with some other data. Ideally it would be best if I could pass back a JSON object containing the HTML and the other data as properties. The problem is that I wanted to put this HTML in partial views in my ASP.NET MVC application and I knew of no easy way to render the view to a string to attach to the JSON object property.

I did a bit of searching and I came across this:

public static string RenderPartialViewToString(Controller controller, string viewName, object model)
{
    controller.ViewData.Model = model;
    try
    {
        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
    catch (Exception ex)
    {
        return ex.ToString();
    }
}

This will work for full views as well as partial views, just change ViewEngines.Engines.FindPartialView to ViewEngines.Engines.FindView.

I added this static method to a class in my ongoing MvcUtilities project. It will happily render a view to a string with no fuss and you can attach it to your JSON object without issue :)