Posts written in March 2015.

  • Published on
    1 min read

    Extension Method To Render Action As String

    A while ago, I wrote a post that showed how you would Render a Partial View As A String. But what if you had a Partial View and wanted to output its action to a string?

    Just like the majority of all other coding problems I encounter, StackOverflow always has the answer. In this case, a clever guy posted this piece of code:

    var sw = new StringWriter();
    PartialViewResult result = Email("Subject", "Body");
    result.View = ViewEngines.Engines.FindPartialView(ControllerContext, "Email").View;
    ViewContext vc = new ViewContext(ControllerContext, result.View, result.ViewData, result.TempData, sw);
    result.View.Render(vc, sw);
    var html = sw.GetStringBuilder().ToString();

    Works well enough. However, I didn't like the thought of having to add all this code inside my controller, especially when I have to output many Partial View actions to a string. So I created an extension method:

    /// <summary>
    /// Renders a Partial View Action to string.
    /// </summary>
    /// <param name="controller">Controller to extend</param>
    /// <param name="partialView">PartialView to render</param>
    /// <param name="partialViewName">Name of Partial View</param>
    /// <returns>Renders Partial View as a string</returns>
    public static string RenderActionToString(this Controller controller, PartialViewResult partialView, string partialViewName)
        using (var sw = new StringWriter())
            partialView.View = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialViewName).View;
            ViewContext vc = new ViewContext(controller.ControllerContext, partialView.View, partialView.ViewData,
                partialView.TempData, sw);
            partialView.View.Render(vc, sw);
            return sw.GetStringBuilder().ToString();

    This extension method can be used in the following way:

    //Access PollController class.
    PollController pc = new PollController();
    //Get the LatestPoll PartialView action and output to string.
    string myPartialView = this.RenderActionToString(pc.LatestPoll(), "../Poll/_LatestPoll");

    Much cleaner!