I have a view where I make take information from a row in Jqgrid and then make an ajax call to the controller using that info as parameteres. The parameters are being passed to the controller however when the it does not perform the action that I desire, I am trying to create a csv file.
View:
function sendParams() {
var selId = jQuery("#list").jqGrid('getGridParam','selrow');
var data = jQuery("#list").jqGrid('getRowData',selId);
$.ajax({
type: "GET",
url: '@Url.Action("ExportToExcel","Home")',
data: {sidx: 'abcd', sord: 'desc', page:1, rows: 100, id: data.selId, rid: data.id, process: data.process, detail_table: data.detail_table, jobGroup: @Html.Raw(Json.Encode(@ViewBag.jobGroup)), date: @Html.Raw(Json.Encode(@ViewBag.DateSelected))},
contentType: "application/json; charset=utf-8",
});
}
<button onclick="function sendParams()">Export</button>
Controller
public ContentResult ExportToExcel(String sidx, String sord, int page, int rows, String id, String process, String detail_table, String jobgroup, String date)
{
var sw = new StringWriter();
List<myModel alist = DAL.ExportExcelConn2.SelectGridItems(sidx, sord, page, rows, rid, process, detail_table, jobgroup, date);
foreach (var item in alist)
{
sw.WriteLine(String.Format("{0}, {1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16}", item.abc, item.sstuff, item.stuff2, item.stuff3, item.stuff4, item.stuff5, item.stuff6, item.stuff7, item.stuff8, item.stuff9, item.stuff10, item.stuff11, item.stuff12, item.stuff13, item.stuff14, item.stuff15, item.stuff16));
}
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=Exportabc" + DateTime.Now + ".csv");
Response.ContentType = "text/csv";
Response.Write(sw);
Response.End();
return Content("Test");
}
If you use
$.ajaxcall you can process the server response inside ofsuccessorerrorcallback. What you really need in case of returning CSV or Excel data is setting of newwindow.location.For example
In the case web browser will automatically open the program on the computer (like Excel).
I recommend you additionally to read the answer which contain ASP.NET MVC Project which export data to Excel (real XLSX file).