C# – Refresh page content after Response.End()

asp.netcnet

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?

Best Answer

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.