我必须这样做,因为我正在使用的页面已经在该区域提交了<form>
,因此我需要使用AJAX来解决<form> within a <form>
问题。< / p>
问题是我的文件没有被发送到网页,我的页面得到200 OK响应状态,但没有发送文件。
在Responses.vbhtml上调用AJAX:
function exportCsv()
{
var formExportSettings = new Object();
var responseIdsList = [];
formExportSettings.formId = '@Model.form.formId.ToString()';
formExportSettings.exporttype = 'csv';
formExportSettings.format = $('input[name=export-format]:checked').val();
formExportSettings.startDate = $('input[id=exportstartdate]').val();
formExportSettings.endDate = $('input[id=exportenddate]').val();
$('input[name=responseId]:checked').map(function() {
responseIdsList.push($(this).val());
});
formExportSettings.responseIds = responseIdsList;
var jsonData = JSON.stringify(formExportSettings);
$.ajax({
url: '/Forms/ExportCsv',
type: 'POST',
dataType: 'json',
data: jsonData,
contentType: 'application/json; charset=utf-8',
success: function (success) {
// never get the success message
var message = success;
console.log(message);
}
});
}
MVC控制器操作:
Function ExportCSV(model As FormsExportSettings) As ActionResult
Dim exportModel As FormsExportModel = New FormsExportModel(model)
Try
Dim fileName = exportModel.form.formName + ".csv"
Response.Clear()
Response.Buffer = True
Response.ClearContent()
Response.ClearHeaders()
Response.ContentType = "text/csv"
Response.AddHeader("Content-Disposition", "attachment;filename=" & fileName)
Response.BinaryWrite(exportModel.writer.ExportToBytes())
Response.Flush()
Response.End()
Catch ex As Exception
End Try
End Function
上一节writer
中的exportModel.writer.ExportToBytes()
属于CsvExport()
类型,它将我的Csv导出为原始UTF8字节。
修改
我刚注意到我收到的CSV文件为Response
。在Chrome中,我可以启动开发控制台,转到网络,然后查看响应,我会看到CSV文件的文本。它只是没有给我保存它的选项。
答案 0 :(得分:0)
我不会直接写回应,而是尝试这样的事情:
Function ExportCSV(model As FormsExportSettings) As FileContentResult
Dim exportModel As FormsExportModel = New FormsExportModel(model)
Dim fileName = exportModel.form.formName + ".csv"
Return File(exportModel.writer.ExportToBytes(), "text/csv", fileName)
End Function
文件功能将处理标题和响应的所有设置,并将返回文件以供下载。