Reputation: 698
I have been up the wall and back again with this. The idea is that when a user clicks a link on a page, the controller method will prepare the data, save it to a memory stream and then serve the file to the user. This is my current code:
public ActionResult Export(int id1, int id2)
{
using (ExcelPackage excelPackage = new ExcelPackage())
{
ExcelWorksheet workSheet = excelPackage.Workbook.Worksheets.Add("Test1");
//Populate worksheet with data...
MemoryStream stream = new MemoryStream();
excelPackage.SaveAs(stream);
stream.Position = 0;
return File(stream, "application/vnd.ms-excel", "myfilename.xlsx");
}
}
My issue is that when this button is clicked, the user is not prompted to grab the file. I have stepped through the method and nothing seems off, but I am reasonably new to MVC and may be missing something.
Any assistance would be welcome.
--EDIT--
I should mention that for the button I am handling the click in a jquery.click function, and I am reaching the above method through AJAX. Would this be an issue in returning a file?
$(".export").click(function () {
var ID1 = '<%: Model.ID1%>';
var ID2= '<%: ViewData["ID2"] %>';
$.ajax({
url: '<%= Url.Action("Export", "Export") %>',
type: "GET",
data: { id1: ID1, id2: ID2},
async: false,
success: function () {
}
});
});
Upvotes: 2
Views: 1188
Reputation: 7847
try next:
$(".export").click(function () {
var ID1 = '<%: Model.ID1%>';
var ID2= '<%: ViewData["ID2"] %>';
var url = '<%= Url.Action("Export", "Export") %>?id1'+ ID1+'$id2'+ID2; // format your url
window.location=url;
}
Not sure about url formatting but you got the point. This worked for me. Let me know if it works for you.
Upvotes: 1