Search code examples
.netjqueryajaxasp.net-mvc-2export-to-excel

Excel Result not giving me anything, but it runs fine


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);
        }
}

Solution

  • 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

    windows.open("yoururl/ExportToExcel?id=yourid&etc...", null, null, null);
    

    And don"t forget to add your arguments.

    Hope this helps