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后面的错误是这样的:
任何帮助将不胜感激。谢谢!
您的ExportToExcel代码在调试器中被击中了吗? – Vadim 2011-02-28 19:37:49
是的,它一直到ExcelResult类中的ExecuteResult方法,这是它将返回MVC中的ActionResult的地方,这就是它弹出错误的地方。 – slandau 2011-02-28 19:39:43
context.Response.Cache.SetCacheability(HttpCacheability.NoCache); 可能会通过https导致此问题。你有https的网站吗?在评论之后尝试一下。 – 2011-02-28 19:46:53