我刚刚将我的MVC视图导出到Excel工作得很好,但是,因为我正在设置location.href,这会让我看到一个充满CSV数据的页面而不是用户点击EXPORT按钮之前的整齐网格结果.
我正在尝试考虑如何更改以下脚本来执行其操作,但只留下页面.我试着调用搜索再次返回服务器但是在运行时用户暂时看到网页上的CSV,这是不好的.
任何想法非常感谢,干杯
$(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; }); //Search(); this fixes because grid is displayed again after csv results }); });
我的控制器代码:
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"); // return File(sw.BaseStream,"text/csv","report.csv"); Renders the same result }