【发布时间】:2019-12-27 04:56:07
【问题描述】:
所以我正在开发一个网站页面,用户可以在其中选择一些元素来制作特定的报告。然后我让他们单击一个按钮,该按钮进行 ajax 调用。此调用(正确)调用控制器中的方法,该方法根据参数创建 .csv 文件。
然而,困难的部分是,在我创建这个文件之后,我希望用户以通常的方式下载它 - 将整个弹出窗口放入下载文件夹等等。
我发现this 堆栈溢出问题或多或少正在做我现在的工作。除了它是在 ASP.NET Core 之前编写的,它并不能真正与我的代码一起使用。这是我现在的代码:
<div class="mybutton">
<button type="button" class="btn btn-info" style="background-color:#587992" id="CreateExcel" onclick="CreateFile()"> Create an Excel File for this Data </button>
</div>
...
<script>
...
function CreateFile(){
array = getParameters();
$.ajax({
type: "POST",
data: { 'array': array },
cache: false,
traditional: true,
url: '@Url.Action("CreateCsvFile")',
success: function (data) {
if (data) {
var element = data;
window.location = 'Download?fileGuid=' + element.FileGuid
+ '&filename=' + element.FileName;
}
}
});
}
</script>
然后这是我的控制器代码:
public ActionResult CreateCsvFile(string[] array)
{
List<OperatorInterventions> TempList = new List<OperatorInterventions>();
//Logic to apply the List to the passed in parameters in this line...
var memoryStream = new MemoryStream();
using (var writer = new StreamWriter(memoryStream, Encoding.UTF8, 1024, true))
using (var csv = new CsvWriter(writer))
{
csv.WriteRecords(TempList);
}
string handle = Guid.NewGuid().ToString();
memoryStream.Position = 0;
TempData[handle] = memoryStream.ToArray();
//return File(memoryStream, "text/csv", "clients.csv");
return new JsonResult(new { FileGuid = handle, FileName = "newreport.csv" });
}
[HttpGet]
public virtual ActionResult Download(string fileGuid, string fileName)
{
if (TempData[fileGuid] != null)
{
byte[] data = TempData[fileGuid] as byte[];
return File(data, "text/csv", fileName);
}
else
{
// Problem - Log the error, generate a blank file,
// redirect to another controller action - whatever fits with your application
return new EmptyResult();
}
}
现在,当我从 Ajax 调用返回到 CreateCsvFile 时,我尝试处理数据。当我单步执行调用时,我可以看到数据/元素包含类似"{"fileGuid":"0123","fileName":"newreport.csv"}" 的内容,但在 window.location 使用的 URL 调用中,它 element.FileGuid 和 element.FileName 最终是“未定义的”。我之前在里面有JSON.parse(data),但这导致了一个错误,JSON.stringify(data) 什么也没做。
此外,我怀疑即使我设法让 fileGuid 和 fileName 不在 url 中未定义,我也不完全确定它是否最终会调用下载文件。
有没有办法修复未定义的?一般来说,有没有更好的方法来执行此 Ajax 调用下载?
谢谢
【问题讨论】:
-
FileGuid!==fileGuid和FileName!==fileName类似 - javascript 对于这些事情区分大小写 ...即@987654331 @ -
I'm not totally sure if it would end up calling the Download file好吧,我对 asp 一无所知,但根据您显示的代码,您可能想要'@Url.Action("Download")?etc'- 考虑到您的 AJAX 请求是'@Url.Action("CreateCsvFile")'- 再次,总计我的猜测
标签: javascript c# ajax asp.net-core