c# - Download Excel file via AJAX MVC -
i have large(ish) form in mvc.
i need able generate excel file containing data subset of form.
the tricky bit shouldn't affect rest of form , want via ajax. i've come across few questions on seem related, can't quite work out answers mean.
this 1 seems closest i'm after: asp-net-mvc-downloading-excel - i'm not sure understand response, , couple years old now. came across article (can't find anymore) using iframe handle file download, i'm not sure how working mvc.
my excel file returns fine if i'm doing full post can't working ajax in mvc.
you can't directly return file download via ajax call so, alternative approach to use ajax call post related data server. can use server side code create excel file (i recommend using epplus or npoi although sounds if have part working). once file has been created on server pass path file (or file-name) return value ajax call , set javascript window.location
url prompt browser download file. end users perspective file download operation seamless never leave page on request originates.
below simple contrived example of ajax call achieve this:
$.ajax({ type: 'post', url: '/reports/exportmydata', data: '{ "dataprop1": "test", "dataprop2" : "test2" }', contenttype: 'application/json; charset=utf-8', datatype: 'json', success: function (returnvalue) { window.location = '/reports/download?file=' + returnvalue; } });
- url parameter controller/action method code create excel file.
- data parameter contains json data extracted form.
- returnvalue file name of newly created excel file.
- the window.location command redirects controller/action method returns file download.
a sample controller method download action be:
[httpget] public virtual actionresult download(string file) { string fullpath = path.combine(server.mappath("~/myfiles"), file); return file(fullpath, "application/vnd.ms-excel", file); }
update september 2016
my original answer on 3 years old, thought update no longer create files on server when downloading files via ajax have left original answer above may of use still depending on specific requirements.
a common scenario in mvc applications reporting via web page has user configured report parameters (date ranges, filters etc.). when user has specified parameters post them server, report generated (say example excel file output) , store resulting file byte array in tempdata
bucket unique reference. reference passed json result ajax function subsequently redirects separate controller action extract data tempdata
, download end users browser.
to give more detail, assuming have mvc view has form bound model class, lets call model reportvm
.
first controller action required receive posted model, example be:
public actionresult postreportpartial(reportvm model){ // validate model correct , contains valid data // generate report output based on model parameters // can excel, pdf, word file - whatever need. // example lets assume we've generated epplus excelpackage excelpackage workbook = new excelpackage(); // populate workbook // generate new unique identifier against file can stored string handle = guid.newguid().tostring() using(memorystream memorystream = new memorystream()){ workbook.saveas(memorystream); memorystream.position = 0; tempdata[handle] = memorystream.toarray(); } // note returning filename handle return new jsonresult() { data = new { fileguid = handle, filename = "testreportoutput.xlsx" } }; }
the ajax call posts mvc form above controller , receives response looks this:
$ajax({ cache: false, url: '/report/postreportpartial', data: _form.serialize(), success: function (data){ var response = json.parse(data); window.location = '/report/download?fileguid=' + response.fileguid + '&filename=' + response.filename; } })
the controller action handle downloading of file:
[httpget] public virtual actionresult download(string fileguid, string filename) { if(tempdata[fileguid] != null){ byte[] data = tempdata[fileguid] byte[]; return file(data, "application/vnd.ms-excel", filename); } else{ // problem - log error, generate blank file, // redirect controller action - whatever fits application return new emptyresult(); } }
one other change accommodated if required pass mime type of file third parameter, 1 controller action correctly serve variety of output file formats.
this removes need physical files created , stored on server, no housekeeping routines required , once again seamless end user.
note, advantage of using tempdata
rather session
once tempdata
read data cleared more efficient in terms of memory usage if have high volume of file requests. see tempdata best practice.
Comments
Post a Comment