But in a couple circumstances you may need to render that view to a string. One case I’ve seen in other blogs is that you may want to return an html string in a JSON response so that script on the calling page can update a partial page section.

The reason I have found to render a view as html is so that it can be passed into a 3rd party component to generate a PDF and then return that PDF response from the action method. To do this I wanted a single line return from my action method to do all the work like the following.

I decided to make it easy and derive PDFActionResult from ViewResult. ViewResult already has the implementation for finding the correct IView required to instantiate an HtmlHelper. Phil Haack already has a good writeup on RenderAction here.

The HtmlHelper RenderAction method is already capable of rendering a view to the ViewContext TextWriter that was passed into the constructor of the ViewContext. In a typical scenario where MVC creates the ViewContext the TextWriter is set to the output stream of the request. This code passes in a StringBuilder instead.

I found it very odd that the ControllerContext does not implement IViewDataContainer since it does have the ViewData property. If it did implement the interface then I would not have had to create the PDFViewDataContainer class.

The creation of the PDF will depend on what PDf library you have available. The PDF tool I used was ExpertPDF. This tool is free if you don’t mind a large watermark in the middle of each page, otherwise it will have a cost.

For all this to work you also need an action method of the partial view name. RenderAction will not work without this. You can mark this action method with ChildActionOnly so that routing does not let a normal request get to this partial view.