ASP.NET Web Forms: Button Not Disabling Before File Download

0

complete working example in ASP.NET Web Forms (VB.NET) that:

  • Disables the button immediately using JavaScript.

  • Downloads a ZIP file.

  • Avoids Response.End() by using CompleteRequest().

  • Optionally shows a loading message during the download.


🔧 ASPX Markup (Download.aspx)

<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Download.aspx.vb" Inherits="Download" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Download File</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnDownload" runat="server"
Text="Click here to download"
OnClick="btnDownload_Click"
OnClientClick="this.disabled=true; document.getElementById('loading').style.display='block';" />
<div id="loading" style="display:none; margin-top:10px; font-weight:bold;">Preparing download...</div>
</form>
</body>
</html>

🔧 Code-Behind (Download.aspx.vb)

Imports System.IO
Partial Class Download
Inherits System.Web.UI.Page
Protected Sub btnDownload_Click(sender As Object, e As EventArgs) Handles btnDownload.Click
' Retrieve docType from query string or use default
Dim docType As String = Request.QueryString("docType")
If String.IsNullOrEmpty(docType) Then docType = "1" ' default or fallback value
' Download the file
DownloadZip(CInt(docType))
End Sub
Private Sub DownloadZip(docType As Integer)
' Simulate a path based on docType (customize as needed)
Dim zipPath As String = Server.MapPath("~/files/sample.zip") ' Adjust this path
Dim file As New FileInfo(zipPath)
If file.Exists Then
Response.Clear()
Response.ContentType = "application/zip"
Response.AddHeader("Content-Disposition", "attachment; filename=" & file.Name)
Response.AddHeader("Content-Length", file.Length.ToString())
Response.WriteFile(file.FullName)
Response.Flush()
' Optional: delete after download (if needed)
' file.Delete()
' Avoid Response.End() — use CompleteRequest()
HttpContext.Current.ApplicationInstance.CompleteRequest()
Else
' Handle missing file (optional)
Response.Write("<script>alert('File not found.');</script>")
End If
End Sub
End Class

✅ Folder Structure Example

/YourProject
├── Download.aspx
├── Download.aspx.vb
├── /files
│ └── sample.zip <-- Place a test zip file here

✅ Summary of Key Features

  • ✅ Button disables before postback using OnClientClick.

  • ✅ Clean file download with Response.WriteFile().

  • ✅ No UI updates lost because all visual changes are handled client-side.

  • ✅ Safe CompleteRequest() instead of Response.End().


Post a Comment

0Comments

Post a Comment (0)