Asp.net

無法在 UpdatePanel 中下載文件

  • October 28, 2020

下面的程式碼可以讓我下載一個Word文件……

  Try
       Response.BufferOutput = True
       HttpContext.Current.Response.Clear()
       HttpContext.Current.Response.Charset = ""
       HttpContext.Current.Response.ContentType = "application/msword"
       HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=myfile.doc")
       HttpContext.Current.Response.Write(s)
       'HttpContext.Current.Response.End()
       HttpContext.Current.ApplicationInstance.CompleteRequest()
       HttpContext.Current.Response.Flush()
   Catch ex As Exception
       Response.Write(ex.Message)
   End Try

但是一旦我添加了一個 UpdatePanel - 它不會下載文件並且不會產生錯誤?閱讀後,我添加了一個觸發器,並將 ControlID 值設置為開始創建 Word doc 文件的按鈕。我嘗試了幾種程式碼組合,但似乎沒有任何效果。有關如何縮小範圍的任何幫助?我也調試過,沒有錯誤顯示。我檢查了我的下載文件夾 - 那裡什麼都沒有,嘗試設置無記憶體(Response.Cache.SetCacheability(HttpCacheability.NoCache)),但沒有奏效。一旦我刪除了 UpdatePanel,那麼一切似乎都正常了嗎?

  <asp:UpdateProgress ID="ProgressUpdate" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
       <ProgressTemplate>
           <img alt="progress" src="../images/loading.gif" />
       </ProgressTemplate>
   </asp:UpdateProgress>
   <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <Triggers>
           <asp:PostBackTrigger ControlID="buttonDownloadFile" />
    </Triggers>
      <ContentTemplate>
       ..

完全迷失在這一點上。任何人都可以提出解決方法或如何解決這個問題?

接受的答案是完全錯誤的。您需要向腳本管理器註冊控制項。我的在母版頁中,這是我用來註冊任何按鈕以進行正確回發的程式碼。

private void MasterPageRegisterButtonForPostBack(Control bt)
       {
           MasterPage masterPage = Master;
           if (masterPage is MainMaster)
           {
               var mainMaster = masterPage as MainMaster;
               if (bt != null && mainMaster.MasterScriptManager != null)
               {
                   mainMaster.MasterScriptManager.RegisterPostBackControl(bt);
               }
           }
       }

我讓它通過以下方式工作:

在我的更新面板中,我配置了可能會強制進行完整回發的控制項,以使下載正常工作。

(我也在使用母版頁,這與史蒂夫的解決方案相同,但在 aspx 中註冊它而不是在後面的程式碼中)

<asp:UpdatePanel runat="server" ID="UpdatePanelDownload" UpdateMode="Conditional" ChildrenAsTriggers="True">
 <ContentTemplate>
     <asp:LinkButton ID="LinkButtonDownload" OnClick="Download_Click" runat="Server">Save XML</asp:LinkButton>
</ContentTemplate>
 <Triggers>
   <asp:PostBackTrigger ControlID="LinkButtonDownlod" />
 </Triggers>
</asp:UpdatePanel>

引用自:https://stackoverflow.com/questions/22081073