Wednesday, February 8, 2012

How to close jQuery ColorBox on file download

Lets suppose you want to display a custom message in a jquery colorbox before a user can download a file, on clicking an agree button on that colorbox, user should be prompted to download/save/open the file and the colorbox should be closed, use the following steps to do so

1. Agree button event handler on the colorbox page should do this

protected void btnAgree_Click(object sender, EventArgs e)
        Session["FilePath"] = YourCompleteFilePath;//put your complete file path here
        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "popupclose", "window.location.href='DownloadFile1.aspx';parent.$.colorbox.close();", true);          
2. Page load on the DownloadFile1.aspx should have the following code

byte[] FileData = new byte[0];
            string filePath = Server.MapPath(Session["FilePath"].ToString());
            FileInfo file = new FileInfo(filePath);
            if (file.Exists)//set appropriate headers
                Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.ContentType = "application/octet-stream";