Reputation: 51
I am having trouble getting a file to be sent to the browser for download prompt. I simply want a button that when pressed, prompts the user to download a .csv file. I have a method to do this, but when I press the button nothing happens at all. I have put breakpoints in the method and it IS being called and run, but no prompt ever occurs. It's as though the button is not attached to anything.
Here is the method (it doesn't currently write the actual csv data just the header, I just want to get it to where it prompts)
protected void btnExport_Click(object sender, EventArgs e)
{
using (StringWriter sw = new StringWriter())
{
sw.WriteLine("sep=|");//define separator
sw.WriteLine("WHY|WONT|THIS|WORK");//header row
//create responce
Response.ClearHeaders();
Response.ClearContent();
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=Participants.csv");
Response.ContentType = "text/csv";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw); //write response body
//Response.End();
Response.Flush();//push it out
Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
Upvotes: 0
Views: 275
Reputation: 51
Turns out the code in question was in an asynchronous postback, and you can't use Response.Flush() during an asynchronous postback.
The solution was found on this page: Response.Write and UpdatePanel
Upvotes: 0
Reputation: 30628
I don't think you should have SuppressContent
there.
Try the following:
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=Participants.csv");
Response.ContentType = "text/csv";
Response.OutputStream.Write(sw);
Response.OutputStream.Flush();
Response.End();
Upvotes: 1