Search code examples
.netasp.net-mvc-2firefoxinternet-explorer-8export-to-excel

Excel Export working in Firefox but not IE


I have Excel Export functionality in my MVC App. The way this works is, I use this line:

window.open((actionUrl + "?id=" + guid + "&viewName=" + viewUrl + "&fileName="  + fileName), null, null, null);

This enables me to pass all of my parameters to the MVC action through the URL. The action looks like this:

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

It then calls the Excel Result which looks like this:

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

All of this works in Firefox but not in IE. Could it be something with the Response headers? That was my first guess but I wouldn't even know where to begin looking for something wrong.

The error that comes back from IE is this: enter image description here

Any help would be greatly appreciated. Thanks!


Solution

  • Don't set

    context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    

    in IE.