Monthly Archives: December 2015

Programmatic View Rendering in ASP.NET MVC

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

public class ControllerBase : Controller
{
    protected string RenderResult(ViewEngineResult result, object model)
    {
        ViewData.Model = model;
        using (StringWriter writer = new StringWriter())
        {
            ViewContext viewContext = new ViewContext(ControllerContext, result.View, ViewData, TempData, writer);
            result.View.Render(viewContext, writer);
            result.ViewEngine.ReleaseView(ControllerContext, result.View);
            return writer.ToString();
        }
    }

    protected string RenderPartialView(string viewName, object model)
    {
        return RenderResult(ViewEngines.Engines.FindPartialView(ControllerContext, viewName), model);
    }

    protected string RenderView(string viewName, string masterName, object model)
    {
        return RenderResult(ViewEngines.Engines.FindView(ControllerContext, viewName, masterName), model);
    }

    protected string RenderView(string viewName, object model)
    {
        return RenderView(viewName, null, model);
    }
}