简体   繁体   中英

MVC C# Return file from controller before return PartialView

Is it possible to return FileContentResult AND PartialView from the same controller? I can't make it working. Main controller code:

...
var generateClass = new GenerateExcel(); // create obj of another class
generateClass.Generate(reports); // generate .xlsx file and save it to server disk
Download(); // ??? download file to client PC via "Save as.." dialog

return PartialView("_PartialReport", reports); // second (main) return and the end of controller

Download() method here:

public FileContentResult Download()
{
    using (HostingEnvironment.Impersonate())
    {
         byte[] doc = System.IO.File.ReadAllBytes(@"C:\temp\BLP.xlsx");
         // doc is OK, it's size == size of .xlsx file
         return File(doc, "application/vnd.ms-excel");
    }
}

No errors but not work.. Help someone please?

Update : ajax code example

// Generate report by creation date
function ConstructReportByDate() {

    var date1 = $('#DateFrom').val();
    var date2 = $('#DateTo').val();

    $.ajax({
        url: '/Reports/ConstructReport',
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        cache: false,
        data: '{"kind":"byDate", "date1":"' + date1 + '", "date2":"' + date2 + '"}'
    })
    .done(function (data) {
        $('#Report').html(data);
    })
    .fail(function (xhr) {
        alert('errorHere');
    });
}

You need to make 2 requests to download the file and to display the partial view, on 2 different actions.

The code to display the partial view seems ok, but the file won't download because you don't set it as the result of the action.

In order to download the file, you have to make a second request. You can't call it using Ajax, because the browser won't downoad it as a file. Just redirect to the file. See this question to see how to do it : Download File Using Javascript/jQuery

If the partial view and the file are based on the same report, the 2 requests may generate it twice, consider adding some cache to avoid generating several times a report with the same parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM