asp.net mvc - Web API return csv file -


i need csv file web api controller. can not "save as" dialog show up. text output shows on page. tried both, calling export jquery , plain old html

controller:

[system.web.http.httpget] public httpresponsemessage export() {     stringbuilder sb = new stringbuilder();     ienumerable<customerdiscount> list = this.subscriberrepository.getsubscribers();      foreach (customerdiscount item in list)     {         sb.appendformat(             "{0};{1};{2};",             item.customername,             item.customernumber,             environment.newline);     }      memorystream stream = new memorystream();     streamwriter writer = new streamwriter(stream);     writer.write(sb.tostring());     writer.flush();     stream.position = 0;      httpresponsemessage result = new httpresponsemessage(httpstatuscode.ok);     result.content = new streamcontent(stream);     result.content.headers.contenttype =         new mediatypeheadervalue("text/csv");     result.content.headers.contentdisposition = new contentdispositionheadervalue("attachment") { filename = "export.csv" };     return result; } 

edit: added line:

result.content.headers.contentdisposition = new contentdispositionheadervalue("attachment") { filename = "export.csv" }; 

still doesn't work

i call this:

<a id="export" href="/relay/billing/export" class="btn btn-primary">export</a> 

and tried this:

$("#export").click(function () {     $.post("/relay/billing/export", { type: $("#discounttype").val() })       .done(function (data) {       }); }); 

still no save box

i not know whether proper protocol how did before. have web page invoke api response file , should handled browser's save dialog.

the html:

<!doctype html> <html xmlns="http://www.w3.org/1999/xhtml"> <head>     <title></title>      <script type="text/javascript">         function save() {             window.open('http://localhost:45719/api/home?id=12', '_blank', '');         }     </script> </head> <body>     <a class="btn btn-primary" onclick="save()">export</a> </body> </html> 

the action:

public httpresponsemessage get(int id) {     memorystream stream = new memorystream();     streamwriter writer = new streamwriter(stream);     writer.write("hello, world!");     writer.flush();     stream.position = 0;      httpresponsemessage result = new httpresponsemessage(httpstatuscode.ok);     result.content = new streamcontent(stream);     result.content.headers.contenttype = new mediatypeheadervalue("text/csv");     result.content.headers.contentdisposition = new contentdispositionheadervalue("attachment") { filename = "export.csv" };     return result; } 

this working me in both chrome , firefox latest.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -