I've seen all the questions and answers around not having code-behind for a view, however I have a case where I need complex logic to generate the presentation (view) layer. I have to output a PDF file based on data obtained from db. Where is the best place to generate this PDF and write to the response stream? Doing response.write from the controller feels very wrong to me, but I would like responses to this, and to using a code-behind file for the view to generate the PDF. I suppose I could encapsulate the data in a viewmodel class and pass that to a Helper method to generate the output as well, what would be considered best practice in this case, specifically having a lot of logic around creating the PDF?
+3
A:
I would create a ActionResult class for this and return that from the controller. The ActionResult class is responsible for writing stuff to the output stream.
Mattias Jakobsson
2010-10-04 14:13:16
Here is a sample of how to do this, not formatted very pretty, but it's something.http://stephenwalther.com/blog/archive/2008/06/16/asp-net-mvc-tip-2-create-a-custom-action-result-that-returns-microsoft-excel-documents.aspx
David
2010-10-04 14:19:59
This one looks a bit better:http://www.jimzimmerman.com/blog/2009/10/06/PdfResult+A+Custom+ActionResult+In+ASPNET+MVC.aspx
David
2010-10-04 14:22:11
A:
The better way to do it is by defining an ActionResult specific for outputting pdf files. This way you can reuse the code easily also in other applications
Francesco Abbruzzese
2010-10-17 09:39:56