I recently needed to implement a facility on a web page to download a file that was defined by a reasonably number parameters, stored on the page as JSON. The first thing I tried was to ajax the request, but that failed as the file never downloaded – I retrieved the data, but it essentially just got ‘swallowed’.

Next I tried using JSON.stringify to populate a hidden field with the JSON value and then submit that. The action that I was posting to was defined with the parameters separately, rather than just string, and I wasn’t able to edit it: I had hoped that ASP.NET MVC 3 might have been able to decode the string but it couldn’t, so that approach failed too. (If I’d been able to amend the action then I could have obviously deserialized the string, but I wasn’t allowed [boo!]).

So in the end I wrote a quick method that would populate my form with hidden fields representing the properties of my JSON model, and that ended up working nicely. Really simple, and would obviously have to be tweaked to handle nested JSON, but it got the job done:

function downloadCurrentReport() {
    var newHiddenInputs = "", i;
    for (i = 0; i < model.length; i++) {
        var nameBase = "model[" + i + "].";
        for (var prop in model[i]) {
            newHiddenInputs +=
                    hiddenField(nameBase + prop, model[i][prop]);
        }
    }
    $("#downloadForm").html(newHiddenInputs);
    $("#downloadForm").submit();
}
    
function hiddenField(name, value) {
    return "<input type='hidden' name='" + name + "' value='" + value + "'/>";
}