【问题标题】:MVC export and download csv fileMVC 导出和下载 csv 文件
【发布时间】:2014-05-05 14:40:58
【问题描述】:

我需要做的是在单击按钮上生成一个 csv 文件根据用户导出的数据,这些文件将具有不同的名称。

 $('#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='" +     + "'";
            }
        });
    });

在我的控制器中,我调用 ExportReport 操作并返回 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);
  }

然后,在 ExportReport 成功后,我试图将文件发送回下载,但似乎无法正常工作。我认为这是因为 ajax 调用是异步调用,并且没有什么可以控制浏览器告诉它下载。任何帮助将不胜感激!

【问题讨论】:

    标签: jquery asp.net-mvc download export-to-csv


    【解决方案1】:

    您应该将文件名传递给 window.location url,并且不要使用单个撇号。

    $('#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;
            }
        });
    });
    

    我相信你可以从这里得到它:

    returnValue.reportExportFile 
    

    【讨论】:

    • 感谢您的工作更改它以发送文件名并且它有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    相关资源
    最近更新 更多