【问题标题】:How to allow a file download from a control wrapped under UpdatePanel?如何允许从包装在 UpdatePanel 下的控件下载文件?
【发布时间】:2012-05-30 04:41:47
【问题描述】:

我有一个 Datalist 控件,它显示缩略图和一个下载图标(ImageButton),Datalist 包裹在 UpdatePanel 下,当用户点击下载图标时,我调用以下函数以允许在用户端下载文件

    protected void dtlSearchDetails_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "dtlImgDownload")
        {
            downloadFile(e.CommandArgument.ToString(), "~/uploads/primary/");
        }
}

功能:

public void downloadFile(string fileName, string filePath)
{
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", fileName));
    Response.WriteFile(filePath + fileName);
}

现在由于 ImageButton / Datalist 包裹在 UpdatePanel 中,我已将其注册为回发控件,并在 Page_Load 上使用 ScriptManager

if (dtlSearchDetails.Items.Count > 0)
{
    foreach (DataListItem li in dtlSearchDetails.Items)
    {
        ImageButton img = (ImageButton)li.FindControl("dtlImgDownload");
        ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(img);
   }
}

现在,当我单击下载图标时,什么也没有发生,我在控制台中收到以下错误:

未捕获的 Sys.WebForms.PageRequestManagerParserErrorException:Sys.WebForms.PageRequestManagerParserErrorException:消息 从服务器收到的无法解析。造成这种情况的常见原因 错误是通过调用 Response.Write() 修改响应时, 响应过滤器、HttpModules 或服务器跟踪已启用。

但是,

同一页面上还有其他控件,例如搜索按钮,它们在此 UpdatePanel 之外,但我已将它们注册为

<trigger>
    <asp:AsyncPostBackTrigger ControlID="btnKeySearch" />
</trigger>

在同一个更新面板中。

当我单击此搜索按钮,然后单击下载图标时,它的行为完全符合预期(在客户端下载文件),并且控制台中没有错误。

我无法找出此解决方法背后的原因。

请帮帮我。

【问题讨论】:

    标签: c# asp.net updatepanel httpresponse datalist


    【解决方案1】:

    您的ImageButtonDataList 中,因此您必须在DataListItemDataBound 事件中执行RegisterPostBackControl

    protected void dtlSearchDetails_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            var imgBtn = e.Item.FindControl("dtlImgDownload") as ImageButton;
            ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(imgBtn);
            // your other code goes here.
        }
    }
    

    【讨论】:

    • 不太确定是否可以在除 Page_Load 之外的其他任何地方重新初始化 ScriptManager 实例,我一定会立即尝试并更新您的信息。感谢您的考虑。
    • Ray :它确实有效,实际上它改变了事件,所以现在当我第一次点击 downloadLink 时,它会下载图像,但是当点击任何其他按钮或网格重新加载,我再次单击下载图标,它给了我同样的错误,所以我认为脚本管理器管理器正在丢失/取消注册控件名称。
    • @Vishal Sachdeva,你是对的。脚本管理器正在失去对其他控件的跟踪,如果页面上有其他控件,它可能会变得复杂。尝试在下载代码后再次调用ItemDataBind,但我不喜欢那种肮脏的解决方法。我的第二个建议是使用Generic Handler 进行文件下载。在您的ImageButton 中,将其href 分配给FileDownload.ashx?id=xtarget=_blank。这样,您就可以通过新请求将下载内容分解到另一个页面。所以UpdatePanel 不在路上了。
    • Ray : 好吧,实际上你绝对在这里,我的第一个想法是只使用 .ashx 处理程序,但我真的找不到一个好的教程开始,我有点经验带网。作为现在的解决方法,我通过将寄存器代码保留在 Page_load 以及 ItemDataBound 事件中来解决这个问题,运行良好,但正如你所说,这些是肮脏的解决方法,而不是正确的方法:) .. 再次感谢您拿出时间。
    猜你喜欢
    • 1970-01-01
    • 2011-03-30
    • 2018-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    相关资源
    最近更新 更多