【问题标题】:In .NET MVC JQuery Ajax call downlaod data as .csv在 .NET MVC JQuery Ajax 调用下载数据为 .csv
【发布时间】:2013-11-20 06:37:57
【问题描述】:

我对控制器进行了 ajax 调用,以获取以下格式的逗号分隔数据,

public ActionResult GetSearchDataforDownloadtoCSV(string pSearchbykeyword, string pRequestCode)
{
   ReportsBE _lReportsBE = new ReportsBE();
   _lReportsBE.SearchKeyword = pSearchbykeyword;
   _lReportsBE.RequestCode = pRequestCode;

     List<ReportsBE> lstResult = new List<ReportsBE>();
     lstResult = _objReports.GetPackagelistAll_Search(_lReportsBE);

    StringBuilder sb = new StringBuilder();
    sb.Append("Request");
    sb.Append(",");
    sb.Append("Description");
    sb.Append("\n");

    foreach (var _RepBE in lstResult)
    {

        if (_RepBE.RequestCode != null)
        sb.Append(Escape(_RepBE.RequestCode));
        sb.Append(",");
        if (_RepBE.Description != null)
        sb.Append(Escape(_RepBE.Description));

        sb.Append("\n");
    }

return Json(sb.ToString());
}

这是我的 HTML,

@Html.LabelFor(model => model.SearchKeyword, "Search Packages by Keyword")
@Html.TextBoxFor(model => model.SearchKeyword, new { style = "width: 500px;" })

<button type="button" id="btnExport" onclick="DownloadCSV()" value="Export to CSV">Export to CSV</button>

这是我的 ajax 调用,

function DownloadCSV() {
        var _pSearchbykeyword = $('#SearchKeyword').val();
        var _pRequestCode = $('#RequestCode').val(); 

        var postData = {
            pSearchbykeyword: _pSearchbykeyword == '' ? '' : _pSearchbykeyword
            , pRequestCode: _pRequestCode == '' ? '' : _pRequestCode
        };

        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetSearchDataforDownloadtoCSV", "Reports")',
            data: postData,
            success: function (data) {
                if (data != null) {
                    // need to code here to through comma seperated data as csv file...
                }
            },
            error: function (xhr, ErrorText, thrownError) {
                alert("No Records Found!");

            }
        });

    }

我的问题是将控制器返回的逗号分隔字符串下载为 .csv 文件。 请帮忙。

我尝试通过如下文件,

var uri = 'data:text/csv;charset=utf-8,' + escape(data);
var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = "SearchList.csv";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);

由于查询字符串的限制,此代码在 chrome 中运行,但在 IE 中不运行。任何帮助将非常感激。谢谢。

【问题讨论】:

    标签: javascript jquery ajax asp.net-mvc csv


    【解决方案1】:

    不要使用 AJAX,而是使用标准 HTML &lt;form&gt;:

    @using (Html.BeginForm("GetSearchDataforDownloadtoCSV", "Reports"))
    {
        @Html.LabelFor(model => model.RequestCode, "Request Code")
        @Html.TextBoxFor(model => model.RequestCode, new { style = "width: 500px;" })
    
    
        @Html.LabelFor(model => model.SearchKeyword, "Search Packages by Keyword")
        @Html.TextBoxFor(model => model.SearchKeyword, new { style = "width: 500px;" })
    
        <button type="submit" value="Export to CSV">Export to CSV</button>
    }
    

    您无法使用 AJAX 请求下载文件的原因是您无法在 javascript 中显示“另存为”对话框。因此,您无法在 AJAX 成功回调中执行任何操作来提示用户保存文件。这就是为什么最简单的解决方案是使用标准表单或直接指向将提供 CSV 文件的控制器操作的锚点。

    【讨论】:

    • 感谢您的回复。但在我的表单中有几个按钮。一个按钮称为“搜索”,它应该在网格中显示结果。另一个按钮用于将结果导出为 csv。在这种情况下,我将如何使用标准 HTML 表单?请帮忙。
    • 然后在点击相应按钮时简单地使用javascript提交表单。不要尝试任何 AJAX 调用,它不起作用。
    • 如果我的两个按钮连接到不同的操作会导致控制器。前任。对于 btnSubmit actionresult 是“LoadGrid”,对于 btnDownload csv “DownlaodCSVData”是操作结果。这意味着我不能简单地通过 js 发布表单。我还必须从页面发送参数。你能指导我吗..请
    • 您可以将表单操作保留为默认提交按钮,当用户单击相应javascript处理程序中的导出到CSV按钮时,您可以在触发提交之前设置表单操作。
    【解决方案2】:

    就个人而言,我会使用FileResult 操作类型而不是通用的ActionResult 方法:

        public FileResult Download(long id)
        {
            var fileData = GetSearchDataforDownloadtoCSV(...);
            // use application/octet-stream for file downloads, saves us needing to
            // infer MIME type
            return File(fileData, "application/octet-stream", "Filename.csv");
        }
    

    这样,您根本不需要使用 AJAX。

    【讨论】:

      【解决方案3】:

      这就是我根据 Darin Dimitrov 和 Richard A. cmets 解决的方法,

      public FileResult GetSearchDataforDownloadtoCSV(string pSearchbykeyword, string pRequestCode)
      {
         ReportsBE _lReportsBE = new ReportsBE();
         _lReportsBE.SearchKeyword = pSearchbykeyword;
         _lReportsBE.RequestCode = pRequestCode;
      
           List<ReportsBE> lstResult = new List<ReportsBE>();
           lstResult = _objReports.GetPackagelistAll_Search(_lReportsBE);
      
          StringBuilder sb = new StringBuilder();
          sb.Append("Request");
          sb.Append(",");
          sb.Append("Description");
          sb.Append("\n");
      
          foreach (var _RepBE in lstResult)
          {
      
              if (_RepBE.RequestCode != null)
              sb.Append(Escape(_RepBE.RequestCode));
              sb.Append(",");
              if (_RepBE.Description != null)
              sb.Append(Escape(_RepBE.Description));
      
              sb.Append("\n");
          }
      
      byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
      return File(buffer, "text/csv", "SearchList.csv");
      }
      

      在我的 Javascript 中,

      function DownloadCSV() {
              var _pSearchbykeyword = $('#SearchKeyword').val();
              var _pRequestCode = $('#RequestCode').val();
      
              pSearchbykeyword= _pSearchbykeyword == '' ? '' : _pSearchbykeyword;
              pRequestCode = _pRequestCode == '' ? '' : _pRequestCode;
      
              window.location = "Reports/GetSearchDataforDownloadtoCSV?pSearchbykeyword=" + pSearchbykeyword + "&pRequestCode=" + pRequestCode;
          }
      

      这就像一个魅力......:)

      【讨论】:

        猜你喜欢
        • 2015-05-13
        • 1970-01-01
        • 1970-01-01
        • 2014-05-27
        • 2020-04-07
        • 1970-01-01
        • 2019-02-20
        • 2018-04-12
        • 2013-02-26
        相关资源
        最近更新 更多