简体   繁体   English

MVC C#在返回PartialView之前从控制器返回文件

[英]MVC C# Return file from controller before return PartialView

Is it possible to return FileContentResult AND PartialView from the same controller? 是否可以从同一控制器返回FileContentResult和PartialView? 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: 此处的download()方法:

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 更新 :ajax代码示例

// 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. 您需要针对2个不同的操作发出2个请求,以下载文件并显示部分视图。

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. 您无法使用Ajax调用它,因为浏览器不会将其作为文件降级。 Just redirect to the file. 只需重定向到文件即可。 See this question to see how to do it : Download File Using Javascript/jQuery 看到这个问题,看看怎么做: 使用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. 如果部分视图和文件基于同一报告,则这两个请求可能会生成两次,请考虑添加一些缓存,以避免多次生成具有相同参数的报告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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