Last Updated: February 25, 2016
·
6.29K
· iondrimba

Render View as String ASP.NET MVC 3/4

using System.IO;
using System.Web.Mvc;

public class RenderRazorViewToString
{
    #region Render

    public string Render( Controller controller, string viewName, object model )
    {
        controller.ViewData.Model = model;

        using ( var sw = new StringWriter() )
        {
            var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

    #endregion
}