2013-07-03 38 views
0

我有一個列表視圖,我想將所有數據導出爲txt文件。由於我需要通過單擊「導出」按鈕來創建3個txt文件。我有一個控制器操作來生成這些文件並將它們作爲zip文件下載。當我點擊導出按鈕時,它會觸發「導出文件」操作。同時我想重定向到「列表」操作,因爲我想刷新視圖。生成的文件下載後重定向到view/refresh視圖asp.net mvc

但問題是我不能同時做兩個任務。那我該怎麼做呢?

這是我的代碼;

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()); 
      } 
     } 

    } 

回答

0

相反,在一個響應中不可能同時執行刷新和文件下載。 當您嘗試時,您會收到異常,例如「發送HTTP標頭後無法重定向」。

你將不得不調整自己的戰略一點點,f.e:

  • 刷新頁面手動某些超時被JS/jQuery的導出按鈕被點擊後後。
  • 額外的元刷新標記返回頁面,這將重定向到下載網址: <meta http-equiv="refresh" content="5,url=DownloadFile.aspx" />

希望它能幫助。

0

由於您的導出將返回一個文件,這聽起來像您只需刷新您開始的視圖(您的列表)。如果是這樣,那麼我所做的就是在選擇下載按鈕幾秒後刷新頁面(我這樣做,因此視圖將顯示更新的下載計數和日期)。

在視圖(您的列表)中,我通常向運行類似於以下腳本的下載按鈕添加一個onclick事件。其他一切都保持不變。

function ReloadPage() 
{ 
    setTimeout(function() { 
     window.location.reload(1); 
    }, 5000); 
}