2

I am not very skilled in ASP.NET and I have tried to:

  1. Update UI elements on an aspx site
  2. at the same time download a file

I have this JS function:

function downloadURL(url) {
            var hiddenIFrameID = 'hiddenDownloader',
                iframe = document.getElementById(hiddenIFrameID);
            if (iframe === null) {
                iframe = document.createElement('iframe');
                iframe.id = hiddenIFrameID;
                iframe.style.display = 'none';
                document.body.appendChild(iframe);
            }
            iframe.src = url;
        };

and this Button server control:

<asp:Button runat="server" ID="Button1" Content="DOWNLOAD" OnClick="Button1_Click" />

in the EventHandler I simply call:

// UPDATE UI

textBoxXY.Text = "Text after file download";

ClientScript.RegisterStartupScript(typeof(MyPage), "myDownloadKey", "downloadURL(" + ResolveUrl("~/MyDownloadHandler.ashx") + ");", true);

What do you think of this approach. It seems to work but...

theSpyCry
  • 12,073
  • 28
  • 96
  • 152
  • But it takes you to another page, or ? I need to do the postback to update the UI elements. – theSpyCry Aug 06 '13 at 18:42
  • Probably you do not need the post back and you can create the parametres for what file to download on client. But if you need to make post back then you can direct send him the file and not reload the page. – Aristos Aug 06 '13 at 18:48

1 Answers1

1

All they have to do with the MyDownloadHandler.ashx headers. If you add there this headers on your handler ashx

 HttpContext.Current.Response.ContentType = "application/octet-stream";
 HttpContext.Current.Response.AddHeader("Content-Disposition", 
                    "attachment; filename=" + SaveAsThisFileName);

then the browser will open the file save browser and not a new tab.

And you only have to do with javascript is

window.location = "MyDownloadHandler.ashx";

or just a simple link.

So to summarize, you have create a lot of code that is not necessary, and you make and a post back, that is also not necessary.

Relative: What is the best way to download file from server
Error handling when downloading file from ASP.NET Web Handler (.ashx)

Aristos
  • 66,005
  • 16
  • 114
  • 150
  • ok but where do I set the textBoxXY.Text = "Text after file download"; ? I would have to do all those things in javascript then.. or ? – theSpyCry Aug 06 '13 at 18:51
  • @PaN1C_Showt1Me Yes you can do that on client side - or you can do what others do (I avoid it) to direct send the file on post back. Or after the page render you just render the `window.location = "MyDownloadHandler.ashx?id=22"` on a script area. – Aristos Aug 06 '13 at 18:52