【问题标题】:Export CSV using jQuery AJAX call使用 jQuery AJAX 调用导出 CSV
【发布时间】:2016-11-09 23:49:18
【问题描述】:

我有一些代码可以将搜索结果导出到 CSV 文件:

$("#exportButton").click(function () {

    var url = "/Stuff/ExportSearchResults";
    var searchInput = readInput();

    $.post(url, searchInput, function (data) {
        // This is where I'm clueless.
        // I'm getting data back but not sure how to make the
        // browser show a prompt to download the file.
        console.log(data);
    });
});

在服务器端(ASP.NET MVC 4)有这样的:

[HttpPost]
public FileResult ExportSearchResults(SearchInput model)
{
    string csv = GenerateCsv(model);
    return File(new UTF8Encoding().GetBytes(csv), "text/csv", "Export.csv");
}

所以好消息是我正在控制台中取回数据。我只是不确定如何让浏览器显示下载文件的提示。

【问题讨论】:

  • 简短回答,你不应该使用 ajax 来完成这种任务,而是直接调用......
  • 成功跨浏览器可能会很痛苦 - 也许FileSaver 会有所帮助
  • window.location.href = '/Stuff/ExportSearchResults';试试这样

标签: javascript c# jquery ajax


【解决方案1】:

对于这个问题,我们可以通过https://stackoverflow.com/users/5349021/sreepathy-sp 发表评论

在客户端

$("#exportButton").click(function () {

       var url = "/Stuff/ExportSearchResults";
       var searchInput = readInput();

       window.location.href = '/Stuff/ExportSearchResults?searchInput='+searchInput ;
});

在服务器端

[HttpGet]
public FileResult ExportSearchResults(string model)
{
    string csv = GenerateCsv(model);
    Stream stream = new MemoryStream(new UTF8Encoding().GetBytes(csv));
    return File(stream , "text/csv", "Export.csv");
}

希望对你有所帮助。

【讨论】:

  • 感谢您的帮助。我需要使用 POST。我们不能在 url 中显示参数。
  • @Aetherix :请您说明一下您的 readInput();。如果它是从数据库中检索到的数据,我们可以在我们的方法 ExportSearchResults 中重新创建 post 模型。
猜你喜欢
  • 1970-01-01
  • 2018-01-19
  • 2013-04-11
  • 2011-06-07
  • 2018-09-25
  • 1970-01-01
  • 2018-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多