1

How can I call a FileResult controller in a MVC project using a ajax call to download a file on the click of a button. I have tried the following code but getting an error every time. If I call it using @Ajax.ActionLink() I am successful but I need to transfer data that I obtain in my jquery only and not in my html.

$('#export_to_excel').click(function () {
    var data = {
        "startIndex": "0",
        "no_of_days": $('#no_of_days').val(),
        "report_id": "A"
    };
    var no_days = $('#no_of_days').val()
    $.ajax({
        url: '@Url.Action("ExportToExcel", "ContentAudit",new { SPHostUrl =SharePointContext.GetSPHostUrl(HttpContext.Current.Request).AbsoluteUri })',
        type: 'POST',
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            alert("success");
        },
        error: function (msg) {
            alert("Error");
        }
    });
});

Controller

public FileResult ExportToExcel(ExportExcel excel)
{
    return File(data1, Response.ContentType,fileName); 
}
  • The excel that I am creating is not saved in my project. It is the form of stream so the above solution is not helping. I am still getting an error. – Jyotsna Wadhwani Mar 23 '17 at 05:02
  • The duplicate clearly explains that you CANNOT use ajax to download a file (just save it to a temporary location, and delete it again, or use `location.href = yourUrl` where `yourUrl` calls the `ExportToExcel(0` method and includes query string values for your parameters –  Mar 23 '17 at 05:07

0 Answers0