I am trying to download an excel file but nothing happens.
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=Daily_Report_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() + "_" + DateTime.Now.Hour.ToString() + "" + DateTime.Now.Minute.ToString() + ".xls");
this.Response.ContentType = "application/vnd.ms-excel";
byte[] temp = System.Text.Encoding.UTF8.GetBytes(htw.InnerWriter.ToString().Replace("<div>", "").Replace("</div>", ""));
grid.Dispose();
htw.Dispose();
return File(temp, "application/vnd.ms-excel");
Similar code is working fine in another page. (I am new to mvc so please bear with me).
I also tried these:
return File("test.xls", System.Net.Mime.MediaTypeNames.Application.Octet, Path.GetFileName("test.xls"));
return File(temp, System.Net.Mime.MediaTypeNames.Application.Octet, "Test.xls");
//return File(temp, "application/vnd.ms-excel");
CSHTML
//window.location.href = "/MeterLog/Export"; // this works but i want the below approach to work:
var fltrFromDate = $("#FromDate").val();
var fltrToDate = $("#ToDate").val();
var type = $('input:radio[name=Status]:checked').val()
box = new ajaxLoader(this, { classOveride: 'blue-loader', bgColor: '#000' });
var dataJSON = { "fltrFromDate": fltrFromDate, "fltrToDate": fltrToDate, "onoff": type };
var str = "";
box = new ajaxLoader(this, { classOveride: 'blue-loader', bgColor: '#000' });
$.ajax({
url: '@Url.Action("Export", "MeterLog")',
type: 'GET',
dataType: 'html',
contentType: 'application/json; charset=utf-8',
data: { "fltrFromDate": fltrFromDate, "fltrToDate": fltrToDate, "onoff": type }
})
NOTE: I just found out that if i hardcode the parameters in the controller and replace the ajax call with window.location.href = "/MeterLog/Export";
then it works! Why?