c# - Custom Excel Export Action -
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); } }
i'm confused on how use action in controller. got internet having hard time figuring out how define in controller , pass data , data ajax call.
any awesome. thanks.
as action results return them action:
public actionresult foo() { someviewmodel model = ... return new excelresult<someviewmodel> ( controllercontext, "~/views/home/foo.ascx", "foo.xlsx", model ); }
in example foo
partial typed view model , contains data.
Comments
Post a Comment