ASP.NET:子用户控件内UpdatePanel内的Response.BinaryWrite

Eri*_*man 1 asp.net user-controls updatepanel parent-child binarywriter

所以我有以下情况:

--Page.aspx-

UpdatePanel
   ListView
      UserControl.ascx
Run Code Online (Sandbox Code Playgroud)

--- UserControl.ascx-

    ListView
        Button|ID:btnDownloadAttachment
Run Code Online (Sandbox Code Playgroud)

我使用以下方法下载附件:

public void OpenDocument(byte[] AttContent, string fileName, string inExtension)
{
    Response.Clear();
    Response.ClearHeaders();
    Response.ClearContent();

    Response.ContentType = "application/pdf";

    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName + inExtension);
    Response.AddHeader("Content-Length", AttContent.Length.ToString());
    Response.BinaryWrite(AttContent);
}
Run Code Online (Sandbox Code Playgroud)

但是由于内容在更新面板中,因此出现以下错误:

“ Sys.WebForms.PageRequestManagerParserErrorException:Sys.WebForms.PageRequestManagerParserErrorException:无法解析从服务器收到的消息。”

b_l*_*itt 5

如果您运行提琴手来查看响应,我想您会看到下载的内容。问题是部分页面呈现。当客户端获得消息时,它认为应该获得页面更新,而是获得一个二进制文件。有两种解决方案:

选项#1,完全禁用页面的部分页面渲染(必须在page_init中完成):

protected void Page_Init(object sender, EventArgs e)
{
  ScriptManager mgr = ScriptManager.GetCurrent(this);
  mgr.EnablePartialRendering = false;
}
Run Code Online (Sandbox Code Playgroud)

选项#2通过控件启动下载来强制回发:

ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(BtnExport);
Run Code Online (Sandbox Code Playgroud)

选项#3创建回发触发器

<asp:updatepanel id="UpdatePanel1" runat="server">
    <triggers>
        <asp:postbacktrigger ControlID="BtnExport"/>
    </triggers>
</asp:updatepanel> 
Run Code Online (Sandbox Code Playgroud)