0

I need to send 500 GUIDs to MVC controller, get some data based of this Id's and return excel sheet. I have a POST method on my controller

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ExportToExcel(List<string> contractIds)
    {
        var contracts = SearchContracts.ExportToExcel(string.Join(",", contractIds));

        byte[] filecontent = ExcelExportHelper.ExportExcel(contracts, "Report", false, null);
        return File(filecontent, ExcelExportHelper.ExcelContentTypeXlsx, "Report.xlsx");
    }

If I do it way of AJAX, I need to have AJAX type: "POST", everything looks OK, but no file is returned to client:

function exportToExcel() {
    var selectedContractsId = getSelectedContracts();

    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportToExcel", "Search")",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(selectedContractsId),
        dataType: "json"
    });
}

and if I do it as standard MVC action and change controller method to HttpVerbs.Get, file is returned to client but I have a problem with URL Too Long exception and update Web.config maxUrlLength parameter is not working for me, because 500 GUIDs is not maximum, you can choose e.g. 10000 GUIDs and it is 370 000 characters in query string.

function exportToExcel() {
    var selectedContractsId = getSelectedContracts();

    location.href = '@Url.Action("ExportToExcel", "Search")?contractIds=' + selectedContractsId;
}
Kicker
  • 606
  • 1
  • 12
  • 27
  • You cannot return a file using ajax. But you can do an ajax call to a method that generates the file and then in the success callback, use `location.href` to navigate to a method which downloads it. –  Sep 18 '17 at 08:05
  • Good idea, but I am not sure if i can imagine how to generate file in one method and how to download it in another method.. can you give me some advice please? – Kicker Sep 18 '17 at 08:08
  • 1
    Just found a dupe that shows how you could do it. –  Sep 18 '17 at 08:09
  • @StephenMuecke thx, problem solved! – Kicker Sep 18 '17 at 09:03

0 Answers0