If you want to upload a file based on some data that you can send to the Controller, it is better not to use Ajax, because it is very difficult to process files through Ajax. One possible solution is to add a link to an additional library .
What I would like to advise you is to use a simple GET request:
In javaScript code:
var urlParams = $.param(dataToSend); window.location.href = "DumpToCSV"+ urlParams;
This way you serialize all your data into a url string and have no problem getting the file through Ajax.
Then in Controller it is better to return FileContentResult or even FileStreamResult if you have really big files. In addition, your model, which is included in the yout controller, can be strongly typed, and MVC ModelBuilder can easily display it from the url string. So the yout data object can be a C # class as follows:
public class CSVData { public string Name { get; set; } public int Count { get; set; } public int SomeId { get; set; } }
And you donβt need to desilialize your data in the controller at all. See here for more details.
public FileContentResult DumpToCSV(CSVData data) { XmlNode xml = data.ToXmlNode(); 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], ","); return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Custom Report.csv"); }
As you can see, there is no need to work with HttpContext in MVC in your case, you can do it in a much cleaner and obvious way.
PS. If your csv object is just byte[] , you can write like this:
return File(csv, "text/csv", "Custom Report.csv");
teo van kot
source share