0

我在我的MVC應用程序中有Excel導出功能。這種工作方式是,我用這條線:Excel導出工作在Firefox,但不是IE

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

這使我所有的參數傳遞到通過URL的MVC行動。動作看起來是這樣的:

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

然後調用Excel的結果看起來像這樣:

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

所有這一切都在Firefox,但不是在IE工作。它可能是什麼與響應頭?這是我第一次猜測,但我甚至不知道從哪裏開始尋找錯誤的東西。

是來自IE後面的錯誤是這樣的: enter image description here

任何幫助將不勝感激。謝謝!

+0

您的ExportToExcel代碼在調試器中被擊中了嗎? – Vadim 2011-02-28 19:37:49

+0

是的,它一直到ExcelResult類中的ExecuteResult方法,這是它將返回MVC中的ActionResult的地方,這就是它彈出錯誤的地方。 – slandau 2011-02-28 19:39:43

+1

context.Response.Cache.SetCacheability(HttpCacheability.NoCache); 可能會通過https導致此問題。你有https的網站嗎?在評論之後嘗試一下。 – 2011-02-28 19:46:53

回答

2

不要在IE設置

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

+0

爲什麼不 - 它對IE有什麼不同? – lstanczyk 2012-02-27 20:28:13

相關問題