Example
Page
<%@ Page Language="C#" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script runat="server"> public string RootUrl { get { Uri requestUri = Context.Request.Url; HttpRequest request = Context.Request; string rootUrl = string.Format("{0}{1}{2}{3}{4}", requestUri.Scheme, Uri.SchemeDelimiter, requestUri.Host, requestUri.IsDefaultPort ? string.Empty : string.Format(":{0}", requestUri.Port), request.ApplicationPath); return rootUrl.EndsWith("/") ? rootUrl : string.Format("{0}/", rootUrl); } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.lblFile.Text = DateTime.Now.ToString("hh:mm:ss"); } protected void GetFile(object sender, EventArgs e) { string fileName = "StudentResults.xls"; this.ClientScript.RegisterStartupScript( this.GetType(), this.GetType().Name, string.Format("window.location.href='{0}DownloadHandler.ashx?fileName={1}'", this.RootUrl, fileName), true); } </script> </head> <body> <form id="form2" runat="server"> <asp:Label runat="server" ID="lblFile" /> <asp:Button runat="server" ID="btnGetFile" Text="GetFile" OnClick="GetFile" /> </form> </body> </html>
lblFile: is there only to demonstrate that page is updating. When you click on GetFile button, it always update the lblFile.Text with the crrent time so the page update is visible to the user. Please note, this lblFile is not essntial, but it is there only for the purpose of demonstration.
Generic Hanlder - DownloadHanlder.ashx
public class DownloadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string fileName = context.Request.QueryString.Get("fileName"); HttpResponse response = context.Response; response.Clear(); response.ContentType = "application/vnd.ms-excel"; response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName)); response.WriteFile(context.Server.MapPath(fileName)); response.Flush(); response.End(); } public bool IsReusable { get { return false; } } }
No comments:
Post a Comment