In MVC3 Razor, how do I get the html of a rendered view inside an action?

I use a static method in a class I called Utilities.Common I pass views back to the client as properties of JSON objects constantly so I had a need to render them to a string. Here ya go:

public static string RenderPartialViewToString(Controller controller, string viewName, object model)
{
    controller.ViewData.Model = model;
    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.ToString();
    }
}

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

Leave a Comment