Question

I'm trying to have a user click a button on a web page to download a CSV file, but I'm having problems sending the correct data to the user. In addition, once the file has been downloaded, I'd like the page to remain "active" i.e. the page can continue to trigger events to the server, such as clicking the Download button again.

This is the code I'm currently using, pieced together from various SO questions:

var sb = new StringBuilder();
string fileName = "data.csv";
// Build CSV file...
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("filename={0}", fileName));
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();

This works so far as presenting the user with an option to open or download the file, but the file also contains the entire markup of the aspx file after the requested data, and the page is left completely inactive.

I'm guessing the problem is with the last two lines of the above code. I've tried using ApplicationInstance.CompleteRequest instead of Response.End, but this doesn't seem to change the outcome. The page is still inactive and the file still has the markup at the end. Can anyone help?

In case it makes any difference in the behaviour of Response, the page is an WebPartPage in SharePoint 2010.

Was it helpful?

Solution

Set the line

HttpContext.Current.Response.AddHeader("content-disposition", "filename={0}", fileName));

to

HttpContext.Current.Response.AppendHeader("content-disposition", String.Format("attachment;filename={0}", fileName));

And set the following property on your button

downloadButton.OnClientClick = "_spFormOnSubmitCalled = false;";

_spFormOnSubmitCalled is a javascript variable that SharePoint uses to stop multiple form submits and it is being set to true when you click the download button.

OTHER TIPS

try this

HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); HttpContext.Current.Response.ContentType = "application/CSV";

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top