3
votes

I have a piece of code that generates a csv file dynamically. The user clicks a button, I prepare the string and then I do so something like:

MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(sb.ToString()));
Response.Clear();
Response.ContentType = "Application/csv";
Response.AppendHeader("content-disposition", String.Format("attachment; filename={0}.csv", fileName.ToString()));
Response.BinaryWrite(stream.ToArray());
Response.End();

The user is then prompted to download or save the newly generated file. The problem is that after this I have to refresh some data in the page. After the Response.End this is not possible anymore.

Any ideas on how to overcome the problem?

2
self redirect through relative link .DestinationPageUrl="~/User/Default.aspx";Rafee
Does the main page refresh have to happen after the file is generated? ie can it happen simultaneously with the downloading of the file?Chris
Can happen simultaneously, yes.Dante

2 Answers

4
votes

This is a common problem and there are lots of ways to solve it which all boil down to needing to create two separate requests to your server. The first one will request your CSV and the second will request your refresh.

With this in mind it's obvious that you can either:

  • Get the user to create both requests (by clicking separately on two links)
  • Use javascript to create both when the user only clicks once

So for example the link that sets off your CSV download could also call a javascript function which causes your data to refresh. The usual way to do this would be to use OnClientClick to call some javascript which will refresh your data.

However you can decide the best way forward based on your app.

3
votes

Maybe clicking on a button will in a new window redirect user to a handler (ashx) which will return the stream / prompt user to save the file?

-or-

Update content first, then send file to a user.