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);
        }
    }
5
  • 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. Commented Jul 20, 2016 at 16:20
  • Thanks for the advice! I will give that a try. Commented Jul 20, 2016 at 22:18
  • What would I use for the return type for the static method that returns the excel document to the Controller? Commented Jul 21, 2016 at 13:57
  • This SO post should get you going in the right direction. Commented Jul 22, 2016 at 21:10
  • Right, I was able to make it happen. Commented Jul 23, 2016 at 0:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.