0

I can't seem to trigger the download file actionresult. I have the following code.

HTML:

<td align="right">
    <label class ="excelLink">Export to excel</label>
</td>

JavaScript:

$('.excelLink').click(function () {
            var url = '@Url.Content("~/Controller/ExcelExport")';
            var statusFilters = new Array();
            var meterFilters = new Array();

            $('[name="CheckBox"]:checked').each(function () {
                statusFilters.push($(this).val());
            });

            $("#lstMeters option:selected").each(function () {
                meterFilters.push($(this).text());
            });

            $.ajax({
                url: url,
                type: 'POST',
                traditional: true,
                dataType: 'json',
                data: {
                    'code1': $("#code1").val(),
                    'code2': $("#code2").val(),
                    'city': $("#city").val(),
                    'date': $("#date").val(),
                    'meterFilter': meterFilters,
                    'statusFilter': statusFilters
                },      
            })
        });

Controller:

        public async Task<FileResult> ExcelExport(string code1, string code2, string city, string date,
        string[] meterFilter, string[] statusFilter)
    {
        DateTime parsedDate = DateTime.MinValue;
        if (!String.IsNullOrEmpty(date))
        {
            parsedDate = DateTime.Parse(date);
        }
        var records = await DataService.GetData(code1, code2, city, parsedDate, meterFilter, statusFilter);
        return DataExcelExport.ExcelExport(records);
    }

In the ExcelExport method, this get returned:

return dataExcelExport.WriteToFile(package, fileName);

Which calls this method:

private FileResult WriteToFile(ExcelPackage package, string fileName)
    {
        return File(new MemoryStream(package.GetAsByteArray()), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
    }

Everything works fine up until it returns the FileResult and nothing happens on the front-end. We implemented the same thing BUT with a Razor ActionLink which doesn't require multiple parameters and that triggers the download of the file just fine.

What am I doing wrong?

  • 1
    Rather than an AJAX post, can you define a form to open a new window and post that (the `
    ` tag can define target="_blank" to open in a new window)? I think the issue is through AJAX - the browser won't prompt to open the file; but the file may be in the AJAX response.
    – Brian Mains Sep 05 '18 at 17:07
  • Hmm yea. That's probably what I thought. AJAX is probably preventing the file to download. Thanks for the help! – Janco de Vries Sep 06 '18 at 05:34

0 Answers0