0

I'm using Spreadsheet Gear to generate and download an excel document to the clients browser. Using the code below the excel document downloads correctly but I need to browser to then redirect the user away from the current page. Where am I going wrong?

Controller

[HttpPost]
public ActionResult Checkout(Models.Checkout m, int id)
{
    var model = this.CreateModel<Models.Checkout>();
    if (model.Checkout().Success)
    {
       this.HandleExport(result.Workbook, "Inspection", new { controller = "Checkout", id = id, action = "Detail" });         
    }
    return View(model);
}

HandleExport

public void HandleExport(IWorkbook workbook, string fileName, object routeValues)
{
    HttpContext.Response.Clear();
    HttpContext.Response.ContentType = "application/vnd.ms-excel";
    HttpContext.Response.AddHeader("Content-Disposition", $"attachment; filename =\"{fileName}_{ DateTime.Now:yyyy-MM-dd_hh-mm-ss}\".xlsx");
    workbook.SaveToStream(HttpContext.Response.OutputStream, FileFormat.OpenXMLWorkbook);
    HttpContext.Response.Flush();
    HttpContext.Response.End();
    HttpContext.Response.RedirectToRoute(routeValues);
}

I've tried setting the RedirectToRoute call after Flush but before End and it still doesnt redirect. If I but the RedirectToRoute before Flush then it redirects but the file doesn't download to the browser.

Bad Dub
  • 1,503
  • 2
  • 22
  • 52
  • 2
    A web request can **fundamentally** only return one response. Any time you are expecting a single request to return two things (like here - you want to download an excel stream / file **and** return a redirect in the same response, which isn't possible) then you need to take a step back and rethink your approach. – mjwills Dec 12 '18 at 11:30
  • I'm open to any ideas you may have – Bad Dub Dec 12 '18 at 11:30
  • 1
    I suspect what you want instead to do is this. Rather than have Page A download a file and redirect to B, instead have Page A redirect to Page B. Page B can **then**, using javascript, use something like https://stackoverflow.com/a/16670517/34092 to trigger the file download. – mjwills Dec 12 '18 at 11:33
  • @mjwills this was a great suggestion. Thanks! – Bad Dub Dec 12 '18 at 11:36

0 Answers0