下载功能在asp.net的更新面板中不起作用

时间:2011-03-28 15:43:43

标签: c# asp.net ajax

我有一个包含FormView的网络用户控件。 formview显示求职者的详细信息。我已经为“下载简历”链接提供了一个按钮,以便admin / HR可以下载简历。我已将此控件放在包含UpdatePanel的aspx页面中。一切正常,除了下载链接。

我在donwload链接按钮上给出了一个命令,并且一个函数与开始下载的命令相关联。

以下是我实施的代码 -

//Command on 'Download' link button within FormView
protected void lnkDownload_Command(object sender, CommandEventArgs e)
{
    if (e.CommandName.Equals("Download"))
    {
        StartDownload(e.CommandArgument.ToString());
    }
}

//My routine to download document
//sFileInfo contains filepath$==$mimetype
protected void StartDownload(string sFileInfo)
{
    string[] d = sFileInfo.ToString().Split((new string[] { "$==$" }), StringSplitOptions.None);
    string filename = d[0];
    string docType = d[1];

    System.IO.FileInfo file = new System.IO.FileInfo(d[0]);

    if (file.Exists)
    {
        Response.Clear();
        Response.AddHeader("Content-Disposition", "attachment; filename=" + d[0]);
        Response.AddHeader("Content-Length", file.Length.ToString());
        Response.ContentType = d[1];
        Response.WriteFile(file.FullName);
        Response.End();
    }
    else
    {
        Server.Transfer("~/Mesgbox.aspx?cat=2");
    }
}

如果删除了更新面板,则代码可以正常工作,但如果使用更新面板,则会生成脚本错误。

有什么建议......?

感谢您分享您的时间。

7 个答案:

答案 0 :(得分:58)

要启动整页回发,请在更新面板中添加回发触发器:

<asp:UpdatePanel runat="server">
    <Triggers>
        <asp:PostBackTrigger ControlID="YourControlID" />
    </Triggers>
    <ContentTemplate>
        .....

答案 1 :(得分:22)

您无法在UpdatePanel部分回发中返回附件,因为ScriptManager使用结果来更新DIV(而不是整个响应)。您尝试做的最简单的修复方法是将下载按钮作为回发控件。这将导致该按钮启动完整回发。以下代码包含在Page_Load

ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(this.lnkDownload);

答案 2 :(得分:5)

您仍然可以从更新面板中触发下载文档。

我有一个更新面板,里面有3个嵌套的中继器。在最内部的转发器中,我使用LinkBut​​tons构建了一系列下载链接,每个链接都包含一个通过webservice获取文档并发送它的命令。

每个转发器都有一个OnItemDataBound方法。在最后一个中继器中,我有以下

        protected void LinkDocRepeaterOnItemDataBound(object sender, RepeaterItemEventArgs e) {
            if(!(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)) {
            return;
                }
            LinkButton linkButton = (LinkButton)e.Item.FindControlRecursive("LinkId");
            var scriptManager = ScriptManager.GetCurrent(this.Page);
            if (scriptManager != null) {
               scriptManager.RegisterPostBackControl(linkButton);
            }
        }

每个Linkbutton现在都会下载一个文档。

答案 3 :(得分:3)

我的情况:

我有一个从sql数据加载的长期运行的excel文件,我希望更新进度面板在创建文件时显示spinner gif,然后从更新面板中下载文件。它比我想象的要复杂。

这个链接在搜索结果中很高,在尝试避免之后,结果发现iframe对我很有用。

iframe async download

这是最终工作的......(这个确切的代码尚未经过测试)

MyPage.aspx ...(内部更新面板,没有触发器)

<asp:Button runat="server" ID="btnExcelExport" Text="Export to Excel" OnClick="btnExcelExport_Click" />

<iframe runat="server" id="ifmExcel" width="0" height="0" marginheight="0" marginwidth="0"
                    frameborder="0" />

MyPage.aspx.cs

        protected void btnExcelExport_Click(object sender, EventArgs e)
        {
            //long running process here, taking advantage of the update progress panel
            var bytes = GetExcelFile();
            //generate a key to pass to the download page to access the file bytes
            var cacheKey = Guid.NewGuid().ToString("N");//N means no hyphens
            //placing the result in cache for a few seconds so the download page can grab it             
            Context.Cache.Insert(key: cacheKey, value: bytes, dependencies: null, absoluteExpiration: DateTime.Now.AddSeconds(30), slidingExpiration: System.Web.Caching.Cache.NoSlidingExpiration);
            ifmExcel.Attributes.Add("src", String.Format("MyDownloadPage.aspx?cacheKey={0}", cacheKey));
        }

... MyDownloadPage.aspx.cs

        protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var bytes = Context.Cache.Get(Request.QueryString.Get("cacheKey")) as byte[];
            Response.Clear();
            Response.AddHeader(
                "content-disposition", string.Format("attachment; filename={0}.xlsx", "Invoice"));
            Response.ContentType = "application/xlsx";
            Response.BinaryWrite(bytes);
            Response.End();
        }
    }

它似乎像任何其他异步回发一样按预期工作。

答案 4 :(得分:0)

您无法在更新面板中使用Response对象。

答案 5 :(得分:0)

                                                                                                                                                                                                                                                                                                                                                           &#39; RUNAT =&#34;服务器&#34;的OnClick =&#34; DownloadFile&#34;&GT;                                                                                                                                                                                                                                                 &#39; RUNAT =&#34;服务器&#34;的OnClick =&#34;的DeleteFile&#34; /&GT;                                                                                                                                                                                                                                                                                   &LT;%----%GT;
                                                             

protected void UploadFile(object sender,EventArgs e)         {             if(FileUpload1.HasFile)             {                 string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);                 string extension =&#34;。&#34; + FileName.Split(&#39;。&#39;)[1] .ToString();                 string FileName_Guid = Convert.ToString(Guid.NewGuid())+ extension;                 FileUpload1.PostedFile.SaveAs(@&#34; C:\ Uploads \&#34; + FileName_Guid);                 string Platform_Config_ID = PlatformConfigID.Value;                 DataTable dt = new DataTable();                 dt = DAL.Upload_File(FileName_Guid,FileName,Platform_Config_ID);

            gv_Files.DataSource = dt;
            gv_Files.DataBind();
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            scriptManager.RegisterPostBackControl(gv_Files);
        }
    }

    protected void DownloadFile(object sender, EventArgs e)
    {
        try
        {                
            LinkButton lnkDownload = (LinkButton)sender;
            GridViewRow row = (GridViewRow)lnkDownload.NamingContainer;
            LinkButton download = row.FindControl("lnkDownload") as LinkButton;
            ScriptManager.GetCurrent(this).RegisterPostBackControl(download);
            string FileName = (sender as LinkButton).CommandArgument.Split(';')[0].ToString();
            string OriginalFileName = (sender as LinkButton).CommandArgument.Split(';')[1].ToString();
            string FilePath = @"C:\Uploads\" + FileName.ToString();
            FileInfo file = new FileInfo(FilePath);
            if (file.Exists)
            {                    
                Response.ContentType = ContentType;
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + OriginalFileName);
                Response.Headers.Set("Cache-Control", "private, max-age=0");
                Response.WriteFile(FilePath);                    
                Response.End();                                     
            }                
        }
        catch (Exception ex)
        {
            // do nothing
        }
    }


    protected void DeleteFile(object sender, EventArgs e)
    {
        string FileName_Guid = (sender as LinkButton).CommandArgument.Split(';')[0].ToString();
        string File_ID = (sender as LinkButton).CommandArgument.Split(';')[1].ToString();
        string Filename = (sender as LinkButton).CommandArgument.Split(';')[2].ToString();
        string Platform_Config_ID = (sender as LinkButton).CommandArgument.Split(';')[3].ToString();
        string FilePath = @"C:\Uploads\" + FileName_Guid;
        File.Delete(FilePath);

        DataTable dt = new DataTable();
        dt = DAL.Delete_File(File_ID, Filename, Platform_Config_ID);

        gv_Files.DataSource = dt;
        gv_Files.DataBind();
    }

答案 6 :(得分:0)

请尝试以下步骤:

  1. <asp:UpdatePanel ID="UpdatePanel5" runat="server" l**UpdateMode="Conditional"**>
    <asp:GridView ID="gv_Files" runat="server" AllowPaging="True" PageSize="7" OnPageIndexChanging="gv_Files_PageIndexChanging" AutoGenerateColumns="false" EmptyDataText="No files uploaded" GridLines="None">
    
  2. (代码背后)UploadFile()

    ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
    scriptManager.RegisterPostBackControl(gv_Files);
    
  3. DownloadFile()

    DownloadFile() --> LinkButton download = row.FindControl("lnkDownload") as LinkButton;
    ScriptManager.GetCurrent(this).RegisterPostBackControl(download);