Scenario:
I have a datatable, the user filters / sort the table and click the export button. Since the datatable is built on server side processing, I had to write the logic for export seperately. When I click the export, the file is not downloading.
Code
[HttpPost]
public FileResult ExportExcelGrid(DataTableAjaxPostModel model)
{
var objFinderModel = _specFinderExportFlow.ConvertToExportable(model);
string dateTime = DateTime.Now.ToString("ddMMyyyy");
var fileDownloadName = "Spec_Finder_Results_" + dateTime + ".xlsx";
return File(objFinderModel, ExcelExportHelper.ExcelContentType,fileDownloadName);
}
Javascript:
$("#lsc-finder-productexport").on("click", function () {
$.ajax({
type: "POST",
url: "@Url.Action("ExportExcelGrid", "SpecFinder")",
data: findertable.ajax.params(),
success: function (response, status, request) {
},
failure: function (response) {
},
error: function (response) {
}
});
});
The call is getting executed, the binary data is returned. How can I download as a file?
This is what I'm getting
Update #2:
I have changed a code like first it'll download the excel file in server and at the ajax success, I'll call the path of the file. which still doesn't work.
Code:
$("#lsc-finder-productexport").on("click", function () {
$.ajax({
type: "POST",
url: "@Url.Action("ExportExcelGrid", "SpecFinder")",
data: findertable.ajax.params(),
success: function (response, status, request) {
window.location.href = response;
},
failure: function (response) {
},
error: function (response) {
}
});
});
C#:
[HttpPost]
public string ExportExcelGrid(DataTableAjaxPostModel model)
{
var objFinderModel = _specFinderExportFlow.ConvertToExportable(model);
string dateTime = DateTime.Now.ToString("ddMMyyyy");
var fileDownloadName = Guid.NewGuid().ToString() + "_Spec_Finder_Results_" + dateTime + ".xlsx";
var webHost = System.Web.HttpContext.Current.Request.Url.Host;
var webPort = System.Web.HttpContext.Current.Request.Url.Port;
var webUrl = webHost + ":" + webPort + "/Content/Export/" + fileDownloadName;
var serverfilename = Server.MapPath("~/Content/Export/") + fileDownloadName;
System.IO.File.WriteAllBytes(serverfilename, objFinderModel);
return webUrl;
}
The file is generated in that Export folder, but its not downloading, the download gets cancelled.