I have a ajax call to the controller to get the comma separated data in the following format,
public ActionResult GetSearchDataforDownloadtoCSV(string pSearchbykeyword, string pRequestCode) { ReportsBE _lReportsBE = new ReportsBE(); _lReportsBE.SearchKeyword = pSearchbykeyword; _lReportsBE.RequestCode = pRequestCode; List<ReportsBE> lstResult = new List<ReportsBE>(); lstResult = _objReports.GetPackagelistAll_Search(_lReportsBE); StringBuilder sb = new StringBuilder(); sb.Append("Request"); sb.Append(","); sb.Append("Description"); sb.Append("\n"); foreach (var _RepBE in lstResult) { if (_RepBE.RequestCode != null) sb.Append(Escape(_RepBE.RequestCode)); sb.Append(","); if (_RepBE.Description != null) sb.Append(Escape(_RepBE.Description)); sb.Append("\n"); } return Json(sb.ToString()); } This is my HTML,
@Html.LabelFor(model => model.SearchKeyword, "Search Packages by Keyword") @Html.TextBoxFor(model => model.SearchKeyword, new { style = "width: 500px;" }) <button type="button" id="btnExport" onclick="DownloadCSV()" value="Export to CSV">Export to CSV</button> This is my ajax call,
function DownloadCSV() { var _pSearchbykeyword = $('#SearchKeyword').val(); var _pRequestCode = $('#RequestCode').val(); var postData = { pSearchbykeyword: _pSearchbykeyword == '' ? '' : _pSearchbykeyword , pRequestCode: _pRequestCode == '' ? '' : _pRequestCode }; $.ajax({ type: 'POST', url: '@Url.Action("GetSearchDataforDownloadtoCSV", "Reports")', data: postData, success: function (data) { if (data != null) { // need to code here to through comma seperated data as csv file... } }, error: function (xhr, ErrorText, thrownError) { alert("No Records Found!"); } }); } My Problem is to download the comma separated string returned from controller as .csv file. Kindly help.
I tried to through the file like below,
var uri = 'data:text/csv;charset=utf-8,' + escape(data); var downloadLink = document.createElement("a"); downloadLink.href = uri; downloadLink.download = "SearchList.csv"; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); This code is working in chrome but not in IE because of query string limitation. Any help would be really appreciated. thanks.