Question

Here's the code snippet from my Controller... it all starts at my Index.

 public ActionResult Index(...){
       //some code here
       return GenerateReport(...);
    }

So far...exporter.GenerateReport() returns the correct path of the generated excel file...

public ActionResult GenerateReport(...){
      string pathOfGeneratedFile = exporter.GenerateReport(...);
      return DownloadFile(pathOfGeneratedFile, "application/vnd.ms-excel");
}


public FileResult DownloadFile(string filePath, string contentType = "application/octet-stream"){
         return File(filePath, contentType, Path.GetFileName(filePath)); 
}

There are actually no errors/exceptions happened along the way.... but I was expecting that I can download the file once it was generated... I manually open the file generated using OpenXMl and it did open and all the information was stored there...

Here is my View... I did some parsing with the value of my button to reflect the GenerateReport user action.... This will submit to the Index action where it determines the user action if it click the generate button...

<input class="btn btn-primary pull-right" type="submit" value="Generate Report" name="userAction"/>

EDIT: I used this also in my view...

@using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "Get", UpdateTargetId = "recordList", InsertionMode = InsertionMode.Replace }))

BTW, once all the operation is finished...I can see a garbage value in my View. I just want the file to be downloaded. Thank you.

Was it helpful?

Solution

The reason why you are unable to download the file is that you are using AJAX async request. An AJAX response cannot contain a file download. You can try something like this in your controller:

public ActionResult Index(...) {
    var fileName = GenerateReport();

    // store the file name somewhere on the server - do NOT pass it through the URL.
    this.TempData["DownloadFileName"] = fileName;
    this.TempData["DownloadContentType"] = "application/vnd.ms-excel";
    this.TempData.Keep("DownloadFileName");
    this.TempData.Keep("DownloadContentType");

    return new JavaScriptResult() { Script = "document.location = \"" + this.Url.Action("Download") + "\";" };
}

public ActionResult Download() {
    return File((string)this.TempData["DownloadFileName"], (string)this.TempData["DownloadContentType"], Path.GetFileName(filePath)); 
}

So your AJAX request will result in a redirect (cannot use RedirectToAction since that will cause to browser to redirect inside the AJAX request). This redirect will then instruct the browser to download the file in a classic request.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top