I have a custom controller extension to return an Excel file as an HttpContext response.
My controller action is as follows:
public ActionResult ExportToExcel()
{
return this.Excel(headers, results, filename);
}
This works perfectly with a normal MVC callback.
I'm trying to create a jQuery UI dialog where the user can enter the file name and press Export. When the Export button is clicked the MVC action will get called in the controller, but the file doesn't get responded in the browser.
My dialog code is:
$("#export-excel").dialog({
autoOpen: false,
modal: true,
title: "Export to Excel",
buttons: {
Export: function () {
$.post("/Search/ExportToExcel",
function () {
$("#export-excel").dialog("close");
});
}
}
});
$("#export-excel-button").click(function () {
$("#export-excel").dialog("open");
return false;
});
And the html:
<div id="export-excel" style="display: none;">
Filename:
<input type="text" value="Results.xls"/>
</div>
<input type="button" value="Export" id="export-excel-button" />
The problem is, that you call your action which returns the file data as an AJAX function.
You have to force the browser to make a regular request to your action to trigger the normal browsers download behavior.
The simplest way is to set the windows.location.href property in javascript:
A sidenote: you should use
Url.Action()
to generate the URL to your action.How to allow download of file, that is returned as binary data from AJAX
I had same problem few days ago. You make AJAX call to your action, so your file is returned in callback function. If you change your button method for:
You will get binnary array of your file in myFileData parameter. I resolve this in that way: