Trying to do csv output on ASP.NET MVC5.
On a screen with multiple parameters and multiple buttons, I post using Ajax.
I'm having trouble downloading files and creating files.
// Here's an excerpt:
$('#download').click(
function(){
var param = new Object();
//param set
if(parking!=null){
$.ajax({
type: "POST",
url: "@Url.Action("CreateCsv", "Csv")",
data —JSON.stringify (param),
contentType: "application/json; charset=utf-8",
datatype: 'json',
success: function() {
debugger
alert("success");
},
failure:function(data){
debugger
alert(data.StatusMessage);
},
error: function(data){
debugger
alert(data.StatusMessage);
}
})
}
}
);
[HttpPost]
public ActionResult CreateCsv (Param Pram)
{
if(Request.IsAjaxRequest())
{
// Retrieving data from DB
// CSV Content Generation
varfileName=string.Format("filename_{0}.csv", DateTime.Now.ToString("yyyyMMddHHmmss"));
vardata=Encoding.UTF8.GetBytes(csvString);
varstream=new MemoryStream(data);
var writer = new StreamWriter(stream);
// var fileStreamResult = new FileStreamResult (stream, System.Net.Mime.MediaTypeNames.Text.Plain);
// fileStreamResult.FileDownloadName=fileName;
// return fileStreamResult;
writer.Write(data);
writer.Flush();
stream.Position=0;
return File (stream, "text/csv", fileName);
}
return null;
}
The last part to return
.
return File (stream, "text/csv", fileName);
Why don't you do this?
return File (stream.ToArray(), "text/csv", fileName);
The article around here has been converted to byte[]
and then returned.
Download ASP.NET MVC files
How to download memorystream to a file?
Perhaps FileResult Class says:
Derived System.Web.Mvc.FileContentResult
System.Web.Mvc.FilePathResult
System.Web.Mvc.FileStreamResult
The FileStreamResult Class may have made it possible to go to MemoryStream
.
Sends binary content to the response by using a Stream
instance.
© 2024 OneMinuteCode. All rights reserved.