views:

86

answers:

4

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.

+4  A: 

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.

Mitchel Sellers
A: 

This may answer your question. Specifically you should use "text/csv" as content type.

Jakob Christensen
+2  A: 

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

Anderson Imes
That did the trick, thanks!
Matt Grande
A: 

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.

Berg