我有一些代码可以将搜索结果导出到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");
}
所以好消息是我在控制台中获取数据。我只是不确定如何让浏览器显示下载文件的提示。
答案 0 :(得分: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");
}
希望这会帮助你。