下载文件异步C#MVC

时间:2016-06-23 11:56:31

标签: c# .net asp.net-mvc file

我创建了一个控制器,通过流程让用户下载CSV文件,但是当它下载时,用户无法在网站上执行任何其他操作。

控制器是:

public async Task ExportClientsListToCSV(string guid)
{
    var search = Session[guid] as SearchVM;

    StringWriter sw = new StringWriter();
    sw.WriteLine("\"Name\",\"Status\",\"E-mail\",\"Phone\"");

    Response.ClearContent();
    Response.AddHeader("content-disposition", "attachment;filename=Exported_Organizations.csv");
    Response.ContentType = "text/csv";
    Response.ContentEncoding = Encoding.UTF32;

    var result = await _adminFacade.OrganizationAllSearchAsync(search.SearchQuery,
                    false,
                    false);

    foreach (var line in result)
    {
        sw.WriteLine("\"{0}\",\"{1}\",\"{2}\",\"{3}\"", 
            line.OrganizationName, line.Status, line.OrgContactEmail, line.Phone);
        }

    Response.Write(sw.ToString());

    Response.End();
}

现在我通过Html.ActionLink("Export", "ExportClientsListToCSV", new {guid = Model.DownloadGuid})解决了这个问题,但我也尝试过:

e.preventDefault();
$.ajax({
    cache: false,
    url: this.exportUrl,
    data: this.$form.serialize()
})
.success(function(data) {
    window.open(this.downloadUrl + '?guid=' + data.fileGuid, '_blank');
}.bind(this));

确保在新窗口/选项卡中打开,但在实际下载文件之前,用户无法在原始选项卡中执行任何操作。无论如何要解决这个问题吗?

0 个答案:

没有答案