2012-04-06 39 views
0

我想下載一個.CSV並將用戶重定向到另一個頁面。下載並重定向

這是我的代碼

protected void btnExport_Click(object sender, EventArgs e) 
    { 
     string attachment = "attachment; filename=" + Request.QueryString["exportName"] + ".csv"; 
     HttpContext.Current.Response.Clear(); 
     HttpContext.Current.Response.ClearHeaders(); 
     HttpContext.Current.Response.AddHeader("content-disposition", attachment); 
     HttpContext.Current.Response.ContentType = "application/ms-excel"; 

     //CODE TO WRITE CSV 
     List<Company> companies = (List<Company>)Session["SelectedCompanies"]; 
     foreach (Company company in companies) 
     { 
      HttpContext.Current.Response.Write(company.Name + ";"); 
      HttpContext.Current.Response.Write(Environment.NewLine); 
     } 



     HttpContext.Current.Response.Redirect("otherpage.aspx", true); 


    } 

但不幸的是,它只是重定向和.CSV的不是下載。

如果我用HttpContext.Current.Response.End();替換HttpContext.Current.Response.Redirect("otherpage.aspx", true);,那麼它只會下載.CSV而不是重定向。

但我想有。

+1

通過AJAX和成功的功能執行重定向下載 – BigMike 2012-04-06 07:05:22

回答

1

在這樣的情況下,我做的是:

  1. 已的iframe隱藏

    < IFRAME ID = 「DownloadIFrame」 可見= 「假」 寬度= 「1」 高度= 「1」 風格= 「顯示:無」> </IFRAME>

  2. 在改變我的頁面內容的同時,給這個iframe一個我沮喪的URL(比如download.ashx)。

在服務器

public string DownloadViaIFrame(Page page, Download download) 
     { 
      string script = string.Format(
      @" 
      var IsDownloaded=false; 

      domReady(function() {{ 
       if (document.getElementById('DownloadIFrame')==undefined) 
           alert('DownloadIFrame not found'); 
          else 
          {{ 
           if (!IsDownloaded) 
           {{ 
            {0}; 
            IsDownloaded=true; 
           }} 
          }} 
      }});", GetJavasciptToDownloadViaIFrame(download)); 


      ScriptManager.RegisterClientScriptBlock(page, typeof(Page), "download", script, true); 

      return script; 
     } 


public string GetJavasciptToDownloadViaIFrame(Download download) 
     { 
      return string.Format("document.getElementById('DownloadIFrame').src='{0}'", GetDownloadLink(download)); 
     } 

這種方式的iFrame命中服務器上的下載腳本,還給該文件由客戶端下載。同時,客戶端看到其頁面的內容而改變,幸福..

好運,

2

據我所知,這兩個行動無法在一個請求中完成,無論是你重定向用戶或給文件。試着用兩個動作來代替它。

0

據我所知,沒有辦法使這兩個行動。 嘗試重定向到otherPage.aspx,並注入在otherPage.aspx一個JavaScript代碼,在onload事件連接到特定的「真正」的下載頁面