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 are 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.
This may answer your question. Specifically you should use "text/csv" as content type.
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
I would let the button post to an .ashx-handler (here's a tutorial on those) and put the code you have written in your post (with some small changes perhaps) in the ProcessRequest method in the handler.
Edit: Also, you might be interested in this question.
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.