skip to Main Content

I am trying to send array with fetch api. but it goes null.

javascript:

const url = "/TMF/DownloadFolderFilesAsZip";

        var data = {
            method: "POST",
            body: JSON.stringify({
                folderFiles: foldersFiles
            }),
            headers: new Headers({
                'content-type': 'application/json'
            })
        }

        fetch(url, data)
            .then(resp => resp.blob())
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = "document" + ".zip";
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
            })
            .catch(() => alert(''));

data:

(2) [{…}, {…}]
0: {fileId: '', folderId: 'e48634fb-23eb-45fa-b974-c83a3032db63'}
1: {fileId: '', folderId: 'c3bdd287-4461-4b5e-95c9-4048e8f34e58'}
length:2
[[Prototype]]: Array(0)

controller:

[HttpPost]
        public async Task DownloadFolderFilesAsZip([FromBody] List<TmfZipFolderFiles> folderFiles)
        {
           ......
        }

c# class:

public class TmfZipFolderFiles
    {
        public Guid fileId { get; set; }
        public Guid folderId { get; set; }
        public Guid tenantId { get; set; }
        public Guid userId { get; set; }
    }

I can’t send the array with the above codes. null data goes to the controller. How can I send the array?

2

Answers


  1. The model you’ve inserted into the body is an object containing an array {"folderFiles":[...]}. Your backend is waiting for the array directly. e.g.: [{...},{...}] You should try editing the body of data.

    JSON.stringify(foldersFiles)
    
    Login or Signup to reply.
  2. I reproduced your issue in my side and after I changed public Guid fileId
    to public string fileId, and using JSON.stringify(foldersFiles), it worked for me.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search