I use this AJAX to call my Excel Export action on the controller:
$("#ExportToExcel").click(function () {
// ajax call to do the export
var urlString = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/ExportToExcel")%>";
var Jsondata =
{
id: GetGUIDValue(),
viewName: "<%= VirtualPathUtility.ToAbsolute("~/Views/Indications/TermSheetViews/Swap/CashFlows.aspx")%>",
fileName: 'Cashflows.xls'
}
$.ajax({
type: "POST",
url: urlString,
data: Jsondata,
success: function (data) {
}
});
});
Here is what the action looks like:
public ActionResult ExportToExcel(Guid? id, string viewName, string fileName)
{
IndicationBase indication = CachedTransactionManager<IndicationBase>.GetCachedTransactions(id.Value);
return new ExcelResult<Chatham.Web.Models.Indications.ModelBase>
(
ControllerContext,
viewName,
fileName,
indication.Model
);
}
Firebug runs through fine, no errors, and the code doesn't error when running either, but nothing pops up on the screen. I am expecting to see a save dialog box to save the excel file.
What am I doing wrong?
EDIT: Here is my custom action,
public class ExcelResult<Model> : ActionResult
{
string _fileName;
string _viewPath;
Model _model;
ControllerContext _context;
public ExcelResult(ControllerContext context, string viewPath, string fileName, Model model)
{
this._context = context;
this._fileName = fileName;
this._viewPath = viewPath;
this._model = model;
}
protected string RenderViewToString()
{
using (var writer = new StringWriter())
{
var view = new WebFormView(_viewPath);
var vdd = new ViewDataDictionary<Model>(_model);
var viewCxt = new ViewContext(_context, view, vdd, new TempDataDictionary(), writer);
viewCxt.View.Render(viewCxt, writer);
return writer.ToString();
}
}
void WriteFile(string content)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.AddHeader("content-disposition", "attachment;filename=" + _fileName);
context.Response.Charset = "";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "application/ms-excel";
context.Response.Write(content);
context.Response.End();
}
public override void ExecuteResult(ControllerContext context)
{
string content = this.RenderViewToString();
this.WriteFile(content);
}
}
You cannot call a file download on a ajax query because the browser will not trigger the file download popup.
Instead of doing an ajax call to your controller method, simply use a
And don"t forget to add your arguments.
Hope this helps
I have my export to Excel implemented using FileContentResult. It takes care of settings response headers for you. There's no point to reinvent the wheel. ;-)
Don't know if it will be useful but I can recommend EPPlus library to load and process Excel files.
Could you try converting your POST to GET and just render tag directly? I don't think IE is picking up content-disposition during AJAX request.