0

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');
    });
}
4
  • Nope. those are two distinct action calls. Commented Dec 26, 2016 at 12:56
  • 2
    You want to send 2 results, so this needs 2 requests. You need to modify the code where you call the action to make 2 requests. Commented Dec 26, 2016 at 13:09
  • what glacasa said, just create an Ajax call on $(document).ready and get the second action as well. Commented Dec 26, 2016 at 13:17
  • @glacasa You mean ajax inside ajax method? Commented Dec 26, 2016 at 13:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, @glacasa

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.