I am working on mechanism to export data in CSV format.
I am sending data in JSON
format using jQuery :
var data = JSON.stringify(dataToSend);
$.post('DumpToCSV', { 'data': data });
Then in the controller I am generating a CSV file :
public ActionResult DumpToCSV(string data)
{
Response.Clear();
XmlNode xml = JsonConvert.DeserializeXmlNode("{records:{record:" + data + "}}");
XmlDocument xmldoc = new XmlDocument();
//Create XmlDoc Object
xmldoc.LoadXml(xml.InnerXml);
//Create XML Steam
var xmlReader = new XmlNodeReader(xmldoc);
DataSet dataSet = new DataSet();
//Load Dataset with Xml
dataSet.ReadXml(xmlReader);
//return single table inside of dataset
var csv = CustomReportBusinessModel.ToCSV(dataSet.Tables[0], ",");
HttpContext context = System.Web.HttpContext.Current;
context.Response.Write(csv);
context.Response.ContentType = "text/csv";
context.Response.AddHeader("Content-Disposition", "attachment;filename=Custom Report.csv");
Response.End();
return null;
}
It returns back the CSV in response, but how do I tell the browser to donwload it?
The difference between this topic : Returning a file to View/Download in ASP.NET MVC Is that I'm using AJAX request