0

I'm using the following to export to excel in an MVC application from a Controller. To do this I have to use some business logic and data objects in the Controller. My export works, but I don't think I should do this in the Controller. I'm new to MVC. Is there a better way to move this logic to the Model and get it out of the Controller?

public void ExportToExcel(PortalAccountMappingModel model)

    {
        var data = model.GetExport();
        var excelReport = new ExcelReportGenerator(Configurations.ReportTemplatesFolder);
        using (ExcelReportData reportData = excelReport.GenerateReport(ExcelReportDataOutputType.StreamData, Constants.PORTAL_ACCOUNT_MAPPING_REPORT_NAME, typeof(PortalAccountMappingReportItem), data))
        {
            byte[] reportByteArray = reportData.DataStream.ToArray();
            Response.Clear();
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", reportData.FileName));
            Response.AddHeader("Content-Length", reportByteArray.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.BinaryWrite(reportByteArray);
        }
    }
GoGetSOme
  • 101
  • 8
  • 2
    You probably don't want to move it to the Model as that kind of breaks the separation of concerns. I would instead create a Utility class with static member functions. This way, you don't need to instantiate the object and you have access to the method even if you're not using the particular model it was intended for. Can always make it generic as well. – Ingenioushax Jul 20 '16 at 16:20
  • Thanks for the advice! I will give that a try. – GoGetSOme Jul 20 '16 at 22:18
  • What would I use for the return type for the static method that returns the excel document to the Controller? – GoGetSOme Jul 21 '16 at 13:57
  • This [SO post](http://stackoverflow.com/questions/25047487/how-to-i-create-and-return-an-excel-file-with-a-controller-in-mvc-4-in-vb-net) should get you going in the right direction. – Ingenioushax Jul 22 '16 at 21:10
  • Right, I was able to make it happen. – GoGetSOme Jul 23 '16 at 00:55

0 Answers0