views:

35

answers:

2

Using this lovely example I am getting some funky results. What I have is:

Protected Sub btnCSV_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCSV.Click

    Response.Clear()
    Response.Buffer = True
    Response.ContentType = "text/csv"
    Response.AppendHeader("Content-Disposition", "inline; filename=" + FileName + ".csv")

    CsvHelper.ProduceCSV(dt, Response.Output, True)

End Sub

But what is happening is that the csv file contains the html output from the page as well as the csv data from the CsvHelper. What gives?

+2  A: 

When btnCSV is clicked your event-handler method sends the CSV data to the response buffer. But once the method finishes executing, the remainder of the page lifecycle continues, sending the normal page markup to the response buffer. This is why you have HTML appended to the CSV.

To prevent this you'll need to end the request as soon as the CSV data has been generated. You'll probably want to call Application.CompleteRequest, or similar, following your ProduceCSV call.

Edit...

After taking a look at the documentation, rather than relying on my memory, it seems that the HttpApplication object isn't exposed within a standard ASP.NET page, in which case you'll probably need to use Response.End instead. Not ideal, but it'll do the trick.

LukeH
+1  A: 

After the click you want to show the normal page + offer the file you created, yes? There's a slight difference: use attachtment instead of inline.

Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", _
  "attachment; filename=""" & filename & """")
Jeroen