程序中有时会因要执行业务比较复杂, 运行时间长的一系统操作, 需要显示如 "执行中 .." 等用户友好提示, 可用ASP.NET AJAX 的 UpdatePanel & UpdateProgress 控件完成. 但若执行结果需要下载文件时, 则会出现执行完成但文件却下载不了的情况. 因为 UpdateProgress 是异步进行中. 解决方法可以建立一个 'DownloadFile.aspx' 页面作辅助, 请见如下主要代码片断
------- Data.aspx -----------
<asp:ScriptManager ID="ScriptManager" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="2" DynamicLayout="true">
<ProgressTemplate>
<img src='<%=CommonUrl.Images %>wait_clock.gif' />
<span id='spanProgressNote'></span>
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
<script language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(initializeRequestHandler);
function initializeRequestHandler(sender, e) {
var postBackElementId = e.get_postBackElement().id;
switch (postBackElementId) {
case '<%= btnSearch.ClientID %>':
spanProgressNote.innerHTML = 'Loading ..';
break;
case '<%= imgExport.ClientID %>':
spanProgressNote.innerHTML = 'Exporting ..';
break;
}
}
</script>
------- Data.cs -----------
protected void imgExport_Click(object sender, ImageClickEventArgs e)
{
...
// SimpleWebUtils.DownloadFile(Response, filePath, Path.GetFileName(filePath)); // 不能直接在当前页下载文件
ScriptManager.RegisterStartupScript(this, this.GetType(), "RegisterStartupScript"
, String.Format("window.navigate('../Control/'DownloadFile.aspx?path={0}');", Server.UrlEncode(filePath)), true);
//ScriptManager.RegisterStartupScript(this, this.GetType(), "RegisterStartupScript"
// , String.Format("window.navigate('{0}');", fileUrl), true); // 用这种方式可以不用 ''DownloadFile.aspx' 页面但下载文件直接打开是用网页方式而不是实际文件方式 (如: Excel)
}
------- DownloadFile.cs -----------
protected void Page_Load(object sender, EventArgs e)
{
string path = Request.QueryString["path"];
SimpleWebUtils.DownloadFile(Response, path, Path.GetFileName(path));
ScriptManager.RegisterStartupScript(this, this.GetType(), "RegisterStartupScript", "window.close();", true);
}