[英]Excel File not downloading using AJAX in MVC4
我正在開發MVC4應用程序,並嘗試通過使用RDLC報告創建Excel文件。 以下是我編寫的用於調用controller方法的AJAX代碼。
var actionUrl = '@Url.Action("MethodName", "ControllerName")';
$.ajax(actionUrl, {
type: 'POST',
data: { merchantAlias: merchantName2, merchantName: merchantName1, sDate: date1, eDate: date2, Incident: whichIncident, call: whichcall },
success: function (d) {
alert(d);
alert("success1");
}
});
我嘗試調試該應用程序,並驗證了控制器方法已正確調用並且正在返回File。 它還顯示“成功”警報消息, 但是在視圖上該文件未下載。
我使用超鏈接嘗試了類似的操作,並將硬編碼的參數發送給該方法,並且文件正在下載。 以下是代碼:
<div><a href="@Url.Action("MethodName", new { merchantAlias = "someAlias", merchantName = "someName", sDate = "2015-01-01 00:00:00", eDate = "2015-01-01 00:10:00", Incident = "0", call = 1 })"> Get Report Excel</a></div>
但是我需要根據用戶在視圖上所做的選擇將動態參數傳遞給我的方法。
以下是在Controller方法內部編寫的代碼:
LocalReport lr = new LocalReport();
lr.ReportPath = Path.Combine(Server.MapPath("~/Reports"), "MerchantExcelReport.rdlc");
DataTable dt = GetDataForExcel(merchantAlias, merchantName, sDate, eDate, Incident, call);
ReportDataSource rd = new ReportDataSource("MerchantExcelDataSet", dt);
lr.DataSources.Add(rd);
string reportType = "Excel", mimeType, encoding, fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + reportType + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
return File(renderedBytes, mimeType);
使用ajax,您無法下載可以使用的文件
window.location = 'your url';
或使用可以使用
jQuery File Download插件來下載文件,您需要做的是從控制器返回文件路徑,並在ajax調用成功時返回
var actionUrl = '@Url.Action("MethodName", "ControllerName")';
$.ajax(actionUrl, {
type: 'POST',
data: { merchantAlias: merchantName2, merchantName: merchantName1, sDate: date1, eDate: date2, Incident: whichIncident, call: whichcall },
success: function (d) {
$.fileDownload(yourfilepath);
}
});
您無法使瀏覽器提示使用ajax下載文件。 您必須將文件存儲在服務器上的某些位置,然后必須使用文件路徑設置window.location。
或者,如果您要使用流而不是存儲文件,只需將要返回文件的代碼的url(而不是任何帶有查詢字符串參數的ajax請求)放入URL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.