0

Good day everyone,

I'm trying to pass my ViewModel from JS to my ASP.NET Core Controller but I'm facing an error code with 500.

Here are my codes:

My Javascript

const myFiles = new FormData(); // I supply this myFiles from my append.
// supposed myFiles has already files inside so don't worry about this.

const myInfo = {
    Id: 0
    Name: "Hello World"
}

const vm = {
    MyInfo: myInfo,
    MyFiles: myFiles
}

axios.post(`/Info/UploadInfo`,
    vm,
    {
        headers:{
            "Content-Type": "multipart/form-data"
        }
    });

My ViewModel

public class MyInfoVm{
    public MyInfo MyInfo {get;set;}
    public IFormCollection MyFiles {get;set;}
}

My Controller

public IActionResult UploadInfo(MyInfoVm vm){
    return Ok();
}

This is working if I remove the VM and solely use one of the fields (either IFormCollection or MyInfo ) in the ViewModel. But the problem is, I need to send multiple parameters in single request. Any help please?

jsonGPPD
  • 987
  • 4
  • 16
  • 31
  • The `IFormCollection` can collect both fields and files, and the Javascript `form` can send both. I would put your `info` as fields in the form. – Tim Mar 21 '18 at 04:04
  • You cannot mix objects and `FormData` - you need to append your other name/pair values (`Id: 0` and `Name: "Hello World"`) to `FormData` - refer [How to append whole set of model to formdata and obtain it in MVC](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) –  Mar 21 '18 at 04:09
  • @Tim do you have simple code sample there? – jsonGPPD Mar 21 '18 at 04:12
  • I'll work one up. – Tim Mar 21 '18 at 04:13
  • what do you mean @Tim – jsonGPPD Mar 21 '18 at 04:20

1 Answers1

1

Javascript

var fileForm = document.createElement('form');
fileForm.enctype = 'multipart/form-data';
var id = document.createElement('input');
id.name = 'id';
id.value = '0';
fileForm.appendChild(id);

var name = document.createElement('input');
name.name = 'id';
name.value = '0';
fileForm.appendChild(name);

var fileInput = document.createElement('input');

fileForm.appendChild(fileInput);
fileInput.id = 'file-input';
fileInput.type = 'file';
fileInput.name = 'file';

var data = new FormData(fileForm);
Tim
  • 2,089
  • 1
  • 12
  • 21