0

In ASP.NET MVC, I am trying to download a file via a post and sending JSON data. This JSON data are filters for the data being displayed on the page via knockout.js. The critieria object is always null. How can I download a file, by sending post data via javascript or a form post? Ive accomplished an ajax download by using a GET, but now I have extra data, like arrays I need to post.

Form

<form method="POST" action="@Model.ExportUrl" >
    <input type="hidden" name="criteria" data-bind="value: ko.toJSON(data())"  />
    <button class="btn"><i class="icon-download-alt"></i> Export</button>
</form>

Request

Request URL:http://localhost:2222/members/eventteams/export?eventId=8998
Request Method:POST
Status Code:500 Internal Server Error
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:128
Content-Type:application/x-www-form-urlencoded
Host:localhost:2222
Origin:http://localhost:2222
Referer:http://localhost:2222/members
User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36
Query String Parametersview sourceview URL encoded
eventId:8998
Form Dataview sourceview URL encoded
criteria:{"page":1,"pageSize":"100","sortOrder":"Team.Name","sortDirection":"ASC"}

Controller

[HttpPost]
public virtual ActionResult Export(int eventId, DivisionTeamsTableCriteria criteria)
{
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341

2 Answers2

0

You can try posting the form to Iframe like this one How do you post to an iframe?

And on the iframe asp.net page, you write the File to response like this Write to CSV file and export it?

  • Iframe can be 1x1 pixels
Community
  • 1
  • 1
Michael B.
  • 2,798
  • 1
  • 14
  • 18
0

Using knockout.js I created this custom binding that works quite well.

ko.bindingHandlers.download = {
        init: function (element, valueAccessor) {

            var value = ko.utils.unwrapObservable(valueAccessor()),
                id = 'download-iframe-container',
                iframe;

            $(element).unbind('click').bind('click', function () {

                iframe = document.getElementById(id);

                if (!iframe) {
                    iframe = document.createElement("iframe");
                    iframe.id = id;
                    iframe.style.display = "none";
                }

                if (value.data) {
                    iframe.src = value.url + (value.url.indexOf('?') > 0 ? '&' : '?') + $.param(ko.mapping.toJS(value.data));
                } else {
                    iframe.src = value.url;
                }

                document.body.appendChild(iframe);

                return false;
            });
        }
    };
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341