Question

What I need to do is generate a csv file on a button click I have all that working calling javascript to use ajax to export the file then I want make it so that the browsers downloads the newly exported file. These files will have different names depending on the data the user is exporting.

 $('#ui_btn_ExportCsv').click(function (event) {
        var formContainer = $("#infoForm");

        $.ajax({
            type: 'GET',
            url: '/Report/ExportReport',
            data: formContainer.serialize(),
            //contentType: 'application/json; charset=utf-8',
            //dataType: 'json',
            success: function (returnValue) {
                window.location = "/Report/Download?file='" +     + "'";
            }
        });
    });

In my controller I call the ExportReport action and return Json

[HttpGet]
        public JsonResult ExportReport(ReportsViewModel reportsViewModel)
        {
//doing the export here and generating the file out on the server....
  return Json(new { success = true, reportExportFile = reportExportPath },JsonRequestBehavior.AllowGet);
}



  [HttpGet]
  public ActionResult Download(string file)
  {   
      string fullPath = Path.Combine(Server.MapPath("~/Report Export"), file);
      return File(fullPath, "application/vnd.ms-excel", file);
  }

Then on the success of the ExportReport I was trying to send the file back to download but cant seem to get it to work. I am thinking it is because of the ajax call being async call and there is nothing to control the brower to tell it to download. Any help would be greatly appreciated!

Was it helpful?

Solution

You should pass the file name to window.location url and do not use a single apostrophe.

$('#ui_btn_ExportCsv').click(function (event) {
    var formContainer = $("#infoForm");
    $.ajax({
        type: 'GET',
        url: '/Report/ExportReport',
        data: formContainer.serialize(),
        //contentType: 'application/json; charset=utf-8',
        //dataType: 'json',
        success: function (returnValue) {
            window.location = "/Report/Download?file=" + yourFileName;
        }
    });
});

I believe you could get it from here:

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