I have an ASP.NET MVC app. On one page I've got a button to allow a user to download a CSV file based on some values on the page set by the user (slider ranges, check boxes, etc.) without leaving the page. The file is returned by my Controller class by a method that returns a FileResult.
Currently, my javascript onClick method is implemented as follows, with a bit of jQuery:
function DownloadCSV() {
var url = <%=Action("DownloadCSV", "Controller")%> + '?' +
$.param({
SomeValue: $("#valuefromform").val(),
OtherValue: $("#anothervaluefromform").val(),
...
});
window.location = url;
}
That part works perfectly, so onto the question: Is it possible to rewrite this method so it 'posts' the query rather than using a 'get' query string?
(I have tried using an AJAX request, which can POST fine, but although I get the file data back this is part of the XHR response and I can't work out how to make it download as a file so if there's a way of doing it that way that would be great too!)
You could setup a form:
<% using (Html.BeginForm("DownloadCSV", "Controller", null, FormMethod.Post, new { id = "myform" })) { %>
<input type="hidden" id="someValue" name="someValue" value="" />
<input type="hidden" id="otherValue" name="otherValue" value="" />
<% } %>
and when time comes to download simply submit this form:
function DownloadCSV() {
$('#someValue').val($('#valuefromform').val());
$('#otherValue').val($('#anothervaluefromform').val());
$('#myform').trigger('submit');
}
Another possibility is to build this form entirely dynamically and inject it into the DOM before submission.
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