Download a string as a file
When the user clicks a button, I want to build a string, then have the user download that string as a file (it's a CSV file).
var response = HttpContext.Current.Response;
response.ClearContent();
response.Clear();
byte[] bytes = Encoding.ASCII.GetBytes(csvtext);
using (var stream = new MemoryStream(bytes))
{
response.AddHeader("Content-Disposition", "attachment; filename=somefile.csv");
response.AddHeader("Content-Length", stream.Length.ToString());
response.ContentType = "text/plain";
stream.WriteTo(response.OutputStream);
}
This is what I have so far, and I have a feeling I'm pretty close, but I get the following error message:
Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error ar开发者_StackOverflow社区e when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. Details: Error parsing near '[The first bit of the CSV file]'.
I'm at a loss, and a deadline is fast approaching. Any help is greatly appreciated.
My guess is that you are in an AJAX Update Panel. If you are doing this type of action it must be done via a postback.
You can't do this with a partial/async postback with Ajax. You'll need to make whatever button you have triggering this download a PostBackTrigger for your UpdatePanel. Details here: http://www.asp.net/Ajax/Documentation/Live/mref/T_System_Web_UI_PostBackTrigger.aspx
精彩评论