我用這個AJAX調用控制器上我的Excel導出動作:Excel的結果沒有給我任何東西,但它運行良好
$("#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) {
}
});
});
這裏是行動的樣子:
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運行良好,沒有錯誤,運行時代碼也不會出錯,但屏幕上沒有任何東西彈出。我期待看到一個保存對話框來保存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);
}
}
謝謝!完美的作品。 – slandau 2011-02-24 16:13:39