I just exported the MVC export view to Excel, however, because I set location.href, it leaves me a page with CSV data, not a neat grid result before the user clicks the EXPORT button.
I'm trying to think about how to modify the following script to do what it does, but leave the page alone. I tried calling search to get back to the server again, but at runtime the user instantly sees CSV on the web page, which is bad.
Any ideas highly appreciated, cheers
$(function() { $('#exportButton').click(function() { var url = $('#AbsolutePath').val() + 'Waste.mvc/Export'; var data = { searchText: $('#SearchTextBox').val().toString(), searchTextSite: $('#SearchTextBoxSite').val().toString(), StartDate: $('#StartDate').val(), EndDate: $('#EndDate').val() }; $('#ResultsList').load(url, data, function() { $('#LoadingGif').empty(); location.href = url + "?searchText=" + data.searchText + "&searchTextSite=" + data.searchTextSite + "&StartDate=" + data.StartDate + "&EndDate=" + data.EndDate; });
My controller code:
public FileStreamResult Export(string searchText, string searchTextSite, string StartDate, string EndDate) { var searchResults = getSearchResults(searchText, searchTextSite, StartDate, EndDate); HttpContext.Response.AddHeader("content-disposition", "attachment; filename=Export.csv"); var sw = new StreamWriter(new MemoryStream()); sw.WriteLine("\"Ref\",\"Source\",\"Collected\""); foreach (var line in searchResults.ToList()) { sw.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\"", line.WasteId, line.SourceWasteTypeId.ToDescription(), line.CollectedDate.ToShortDateString())); } sw.Flush(); sw.BaseStream.Seek(0, SeekOrigin.Begin); return new FileStreamResult(sw.BaseStream, "text/csv");