FileContentResult return – 2 different controller methods, different result

I am using ASP.NET Core and ClosedXML to generate an Excel export.

Here is the controller method that DOES return an .xlsx file to the browser. The method gets called from a .cshtml page:

<form id="downloadLoanEvents" asp-action="DownloadLoanEventsLog" asp-controller="Lender" asp-route-id="@Model.LoanFileId" method="post">
    <div class="form-group">
        <input type="submit" value="Submit" />
    </div>
</form>

This is the DownloadLoanEventsLog controller method:

[HttpPost]
public async Task<IActionResult> DownloadLoanEventsLog(string id)
{
    var user = await _userManager.GetUserAsync(HttpContext.User);
    var loan = _unitOfWork.LoanFiles.GetById(id);

    var list = eventLogService.GetLoanFileEventLog(id, _unitOfWork, user);
    string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    string fileName = $"Loan-{loan.LoanNumber}-EventsLog.xlsx";

    try
    {
        using (var workbook = new XLWorkbook())
        {
            IXLWorksheet worksheet = workbook.Worksheets.Add("Events");
            worksheet.Cell(1, 1).Value = "EventDate";
            worksheet.Cell(1, 2).Value = "LoanNumber";

            int index = 2;

            foreach (var row in list)
            {
                worksheet.Cell(index, 1).Value = row.EventDateTimeDisplay;
                worksheet.Cell(index, 2).Value = row.LoanNumber;
                index++;
            }

            using (var stream = new MemoryStream())
            {
                workbook.SaveAs(stream);
                var content = stream.ToArray();
                return File(content, contentType, fileName);
            }
        }
    }
    catch (Exception ex)
    {
        return RedirectToAction("CloseLoan", new { id = id }).WithWarning("", "Exporting Loan File Events Failed");
    }
    finally
    {
    }
}

The DownloadLoanEventLog method works great. I quickly get an expected Excel file to the browser.


Here is the controller method that DOES NOT return an .xlsx file to the browser.

The method is nearly identical to the 1st method, but this export kicks off in Ajax call to send a json array of data to the controller.

var rows = $("#report").jqxGrid('getrows');

var loans = [];

for (var i = 0; i < rows.length; i++) {
    var row = rows[i];
    loans.push({
        "loanNumber": row.loanNumber,
        "loanType": row.loanType,
    });
}

var jqxhr = $.ajax({
    data: JSON.stringify(loans),
    contentType: "application/json",
    url: "/Reports/ExportLoansReport",
    type: "POST"
});

This is the ExportLoansReport controller method:

[HttpPost]
public IActionResult ExportLoansReport([FromBody] List<LoansReportExportViewModel> model)
{
    string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    string fileName = $"Loans-Export.xlsx";

    try
    {
        using (var workbook = new XLWorkbook())
        {
            IXLWorksheet worksheet = workbook.Worksheets.Add("Loans");
            worksheet.Cell(1, 1).Value = "LoanNumber";
            worksheet.Cell(1, 2).Value = "LoanType";
            
            int index = 2;

            foreach (var row in model)
            {
                worksheet.Cell(index, 1).Value = row.LoanNumber;
                worksheet.Cell(index, 2).Value = row.LoanType;
                
                index++;
            }

            using (var stream = new MemoryStream())
            {
                workbook.SaveAs(stream);
                var content = stream.ToArray();
                return File(content, contentType, fileName);
            }
        }
    }
    catch(Exception ex)
    {
        return Json("some fail msg");
    }
}

ExportLoansReport gets a valid json object in the [FromBody] parameter, and the code does not throw any exception at all. Once return File fires, nothing happens, no file is returned to the browser.

I suspect this issue is because the request was made from the client side but I am not sure how to fix it.

3

It seems that ajax itself is not designed to support downloading file scenarios. You might want to have a try with ajaxfiledownload package which supports fetching files from server in an asynchronous way.

New contributor

Parker is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật