Reputation: 75
I have an action that returns (downloads) an excel file in the following manner:
public IActionResult CreateExcelFile(string id, int xx, string start, string end) {
//Some additional code...
// ....
// ....
var file = File(doc, "application/vnd.ms-excel");
file.FileDownloadName = filename + " " + id + ".xlsx";
return file;
}
So far, I have triggered this action from a view like this:
<div id="myDiv">Some Content</div>
And lastly the JavaScript:
$(function excelFunction() {
$('#myDiv').click(function () {
alert("Initiate excel export")
var start = $('#startDateTextBox').val();
var end = $('#endDateTextBox').val();
$.ajax({
type: 'GET',
url: '/Customer/CreateExcelFile',
data: { id: 'FVM10000', xx: '4', start: start, end: end },
success: function (response) {
if (response.type == "success") {
alert("success")
}
else {
// Do something else
alert("failure")
}
}
});
});
});
I enter the debugging mode and see that the action is indeed called with the correct parameters, however, after the action is executed, no file is returned (or downloaded). I get an alert message saying "failure", which indicates that the response was not completed.
Any ideas what I am doing wrong?
Upvotes: 2
Views: 5140
Reputation: 218722
Do not use ajax for file downloads. Do the normal HTTP request to your action method.
$('#myDiv').click(function () {
var start = $('#startDateTextBox').val();
var end = $('#endDateTextBox').val();
var url='/Customer/CreateExcelFile?id=FVM10000&xx=4&start='+start+'&end='+end;
window.location.href=url;
});
I would also recommend using the html helper method to generate the correct relative path to the base portion of your action method. you can execute the Url.Action
helper method and store the result of this call in an html 5 data attribute in your div.
<div id="myDiv" data-url="@Url.Action("CreateExcelFile","Customer")">Some Content</div>
Now in the script read this value and do the querystring concatenation.
$('#myDiv').click(function () {
alert("Initiate excel export")
var start = $('#startDateTextBox').val();
var end = $('#endDateTextBox').val();
var url=$(this).data("url")+"?id=FVM10000&xx=4&start="+start+"&end="+end;
window.location.href=url;
});
Upvotes: 3