简体   繁体   中英

Downloading a file with Knockout bindings, ASP.NET MVC stack and no Razor

Trying to find a resource that could point me in the right direction for downloading a file with this particular stack. It's more challenging than it seems, especially since I'm unable to use Razor in accordance with house rules.

The code execution can get from the markup, to the knockout, and then the C#, but it doesn't start a download like I would expect in ordinary webforms non-MVC ASP.NET.

mark up:

<div class="row">
    <div class="col-2"><img data-bind="attr: {src: image}, click: $root.downloadFile/></div>

the knockout/javascript call:

self.downloadFile = function(e){
    if(e) {
        attachmentId = e.id;
        helpers.ajax.getJson(root, "/Files/DownloadFile/", {fileId: attachmentId }, function(x){
        attachmentId=0;
        getFiles();
        });
}

... related javascript functions called here:

helpers.ajax.getJson = function(path, url, data, onSuccess, onError){
    helpers.ajax.async('GET', path, url, {
        data: data,
        cache: false,
        async: true,
        error: onError,
        success: onSuccess
    });
};

function getFiles(){
    self.files([]);
    helpers.ajax.getJson(root, "/Files/GetFiles",
    { profileId: self.ProfileId() },
    function (files) {
        if(files) {
        $.each(files, function (i, v) {
            self.files().push(new file(v.AttachmentId, v.FileTypeDescr, v.FileExtension, v.FileName, v.UploadedBy, v.UploadDate, v.CompletionDate));
        self.files.valuehasMutated();
        });
    }
});

}

C#

public FileResult DownloadFile(int fileId)
{
    ODSAPI.AttachmentFile file = FileFunctions.GetById(fileId); 
    if(file != null)
    {
        return File(file.FileData, file.ContentType);
    }
    return null;
}

this returns the correct file information and the bits from the database when I step through the code and view the file variable.

you could use http://danml.com/download.html to download file from javascript AJAX return

for exmaple

     download(data, 'Export.csv', 'application/csv');

where data will be return from your ajax request and file name and file type.

The JSON call in the Javascript was incorrect as it called for a JSON object. Rather, it should have been:

window.open(root + "/Files/DownloadFile?fileId=" + attId, '_blank');

instead of helpers.ajax.getJson()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM