'Web API return csv file
I need to get a csv file from web api controller. I can not get "Save As" dialog to show up. Only text output shows up on the page. I tried both, calling Export from jquery and also 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 this line:
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
still doesn't work
I call it like this:
<a id="export" href="/Relay/Billing/Export" class="btn btn-primary">Export</a>
and also tried it like this:
$("#export").click(function () {
$.post("/Relay/Billing/Export", { type: $("#discountType").val() })
.done(function (data) {
});
});
Still no Save As box
Solution 1:[1]
You cannot have a download dialog if you call your API from an AJAX call. Either make it a regular link (for APIs using GET) or, if you need it to be a POST, have it to post to a new window using a regular form with target="_blank".
So, either <a href="/Relay/Billing/Export?type=...">click here</a>, or
<form method="post" target="_blank" action="/Relay/Billing/Export">
<input id="discountType" name="type"/>
<input type="submit">Export</input>
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ulu |
