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);
}
}我真的很困惑如何在我的控制器中使用这个动作。这是我从互联网上得到的,但我只是很难弄清楚如何在我的控制器中定义它,如何将数据传递给它,并从AJAX调用中获取数据。
任何帮助都是很棒的。谢谢。
发布于 2011-02-24 15:12:37
与所有操作结果一样,您将从操作中返回它们:
public ActionResult Foo()
{
SomeViewModel model = ...
return new ExcelResult<SomeViewModel>
(
ControllerContext,
"~/Views/Home/Foo.ascx",
"Foo.xlsx",
model
);
}在本例中,Foo partial被强类型化为视图模型并包含数据。
https://stackoverflow.com/questions/5096370
复制相似问题