I am new to using ASP.NET MVC 4 with Web Api.
I want to allow user to download a file, this file I will be creating on the server side. For creating the file I have managed to get hold of the following code
[ActionName("Export")]
public HttpResponseMessage PostExportData(SomeModel model)
{
string csv = _service.GetData(model);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StringContent(csv);
//a text file is actually an octet-stream (pdf, etc)
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
//we used attachment to force download
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "file.csv";
return result;
}
HOW TO CALL THIS WEB API METHOD USING JQUERY ?
But I am not sure of how to call this web api using jquery and make it return me a file, with a "save as / open" option that you normally get when downloading any file.
Can some one please help me and guide me in how to make the call and download the file. Thanks.
You can do something like this inside the view where you want to use jquery. I assume the name of the controller is ExportController. You also have to break down the model variables, or alternatively collect the model inside HttpResponseMessage PostExportData(SomeModel model)
via some other way.
html:
<a class="export">export</a>
javascript:
<script>
$('a.export').click(function(e) {
e.preventDefault(); //stop the browser from following
window.location.href = '@Url.Action('Export', 'ExportController', new { property = model.property, property = model.property2 })';
});
</script>
To use POST
function UpdateForm(modelObject) {
if ($('#hidden-form').length < 1)
{
$('<form>').attr({
method: 'POST',
id: 'hidden-form',
action: '@Url.Action('Export', 'Export')'
}).appendTo('body');
}
$('#hidden-form').html('');
for(var propertyName in modelObject) {
$('<input>').attr({
type: 'hidden',
id: propertyName,
name: propertyName,
value: modelObject[propertyName]
}).appendTo('#hidden-form');
}
}
$('a.export').click(function(e) {
e.preventDefault();
var modelObject = { property1 : "property1" };
UpdateForm(modelObject);
$('#hidden-form').submit();
});
Then you can just post #hidden-form
via js which will trigger the file download
Update: This is a full example for posting, and its not checked for typos etc so debug any minor errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With