Tuesday, September 20, 2011

ASP.NET MVC Render a View to a String

Sometimes it can be worthwhile to capture the content of a controller-generated view as a string for returning as JSON or as HTML email body content or whatnot.

Via Crafty Code:

public abstract class MyBaseController : Controller 
{
    protected string RenderPartialViewToString()
    {
        return RenderPartialViewToString(null, null);
    }

    protected string RenderPartialViewToString(string viewName)
    {
        return RenderPartialViewToString(viewName, null);
    }

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

    protected string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter()) {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
}

You can optionally replace ViewEngines.Engines.FindPartialView with ViewEngines.Engines.FindView.

No comments:

Post a Comment