I am trying to create and download excel file using the following code. It works fine when I use window.open("Export");
in cshtml to call controller method. But it does not work when I make following ajax call. The reason I want to do it using ajax call is because I will be passing parameter to he controller. (I am yet to write logic to use those parameters.)
CSHTML
var actionUrl = '@Url.Action("Export", "TrendsData")';
$.ajax({
url: actionUrl,
type: 'POST',
cache: false,
data: { col: FinalColumns.toString() },
success: function (result) {
}
});
CONTROLLER:
public void Export(string col)
{
var grid = new GridView();
var data = TempData["InstanceDataList"];
List<InstanceDataLog> lst = new List<InstanceDataLog>();
List<EToolsViewer.APIModels.InstanceDataLog> lstrefined = new List<InstanceDataLog>();
lst= (List<EToolsViewer.APIModels.InstanceDataLog>)TempData["InstanceDataList"];
var r= lst.Select(e => new {e.CBlk_Avg_Hz, e.CBlk_Avg_MW}).ToList();
grid.DataSource =r;
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=Trendsdata_" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
TempData["InstanceDataList"] = data;
Response.End();
}
With the above code I am able to call controller method but file does not download whereas problem with using window.open("Export");
is that I can not pass parameters.
I have found out that if I again put window.location = '@Url.Action("Export", "TrendsData",new { col = "a,b,c" })';
in the success method , it works. Is there an explanation for this ? Why do I have to make two calls?