Sunday, August 22, 2010

How to update a page at the same time we download a file in

When we use Response.WriteFile(Results.xls), serve you the desired file, but in such cases the underline page does not get refreshed due to no html reponse generated by the server. To get the page updated with the same time when we download a file we may consider handling the file download to separate request. This request can be handled by a generic handler in
<%@ Page Language="C#"  %>
<html xmlns="">
<head id="Head1" runat="server">
    <script runat="server">
        public string RootUrl
                Uri requestUri = Context.Request.Url;
                HttpRequest request = Context.Request;
                string rootUrl = string.Format("{0}{1}{2}{3}{4}",
                    requestUri.IsDefaultPort ? string.Empty : string.Format(":{0}", requestUri.Port),
                return rootUrl.EndsWith("/") ? rootUrl : string.Format("{0}/", rootUrl);
        protected override void OnLoad(EventArgs e)
            this.lblFile.Text = DateTime.Now.ToString("hh:mm:ss");
        protected void GetFile(object sender, EventArgs e)
            string fileName = "StudentResults.xls";
                this.GetType(), this.GetType().Name,
                    this.RootUrl, fileName), true);
    <form id="form2" runat="server">
        <asp:Label runat="server" ID="lblFile" />
        <asp:Button runat="server" ID="btnGetFile" Text="GetFile" OnClick="GetFile" />

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.ContentType = "application/";
        response.AppendHeader("Content-Disposition"string.Format("attachment;filename={0}", fileName));
    public bool IsReusable
            return false;

No comments:

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...