In MVC anytime you have to allow the user to download something (pdf, csv, excel, etc.,..) from values generated at runtime, I find it much cleaner to create a new Result type of ActionResult. To say the least it makes the code much more cleaner by abstracting away the logic of actually transforming your data into one of these file formats. By creating a new class to handle the transformation, relieves your Controller from that duty and enforces separation of concerns – which is always a good thing. Here is my implementation of a CsvResult that takes in an IEnumerable of “reference” type and converts it into a comma separated value file that users can download:
And here is the CsvResult being used in the Controller class:
The reason for creating the CsvResult abstract class is so that I can simply do “public CsvResult DownloadCsv()” rather than “public CsvResult<Product> DownloadCsv()”, which looks ugly and too ceremonious.