0

我有一个列表视图,我想将所有数据导出为 txt 文件。作为要求,我需要通过单击导出按钮创建 3 个 txt 文件。我有一个控制器操作来生成这些文件并将它们作为 zip 文件下载。当我单击“导出”按钮时,它将触发“ExportFiles”操作。同时我想重定向到“列表”操作,因为我想刷新视图。

但问题是我不能同时完成这两项任务。那么我该怎么做呢?

这是我的代码;

    public virtual ActionResult List()
    {
        // Code : showing my list
        return view();
    }

    public virtual ActionResult ExportFiles()
    {
        // Code : Generating files
        return new ZipResult(filePath, fileName + ".zip");
        // HERE I WANT TO REFRESH MY VIEW
    }

    public class ZipResult : ActionResult
    {
        private readonly string _filePath;
        public string Filename { get; set; }

        public ZipResult(string filePath, string fileName)
        {
            _filePath = filePath;
            Filename = fileName;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var response = context.HttpContext.Response;
            response.ContentType = "application/gzip";
            using (var zip = new ZipFile())
            {
                zip.AddFile(_filePath);
                zip.Save(response.OutputStream);
                var cd = new ContentDisposition
                {
                    FileName = Filename,
                    Inline = false
                };
                response.Headers.Add("Content-Disposition", cd.ToString());
            }
        }

    }
4

2 回答 2

0

相反,不可能在一个响应上同时进行刷新和文件下载。当您尝试时,您将收到“发送 HTTP 标头后无法重定向”之类的异常。

你将不得不稍微调整你的策略,fe:

  • 单击导出按钮后,在 JS/jQuery 超时后手动刷新页面。
  • 返回带有附加元刷新标签的页面,该标签将重定向到下载网址: <meta http-equiv="refresh" content="5,url=DownloadFile.aspx" />

希望能帮助到你。

于 2013-12-31T19:57:17.713 回答
0

Since your export will return a file, it sounds like you simply need to refresh the view that you're starting from (your list). If that is the case, then what I do is have the page refresh a few seconds after a download button is selected (i do this so the view will show updated download counts and date).

In the View (your list) I typically add an onclick event to the download button(s) that run a script similar to below. Everything else stays the same.

function ReloadPage()
{
    setTimeout(function () {
        window.location.reload(1);
    }, 5000);
}
于 2015-06-01T20:14:51.880 回答