Is there a way to add array elements to a formData object, so net core [FromForm] will deserialize them correctly?

Viewed 1940

So, I'm using the feth api to do posts, and it's generally working out really well. But I am having one issue, say I have the following two models:

public class Contact
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Phone> Phones { get; set; }
}

public class Phone
{
    public string Number { get; set; }
    public string Model { get; set; }
}

Now, I want to create a formData object from the html form, which adds the strings and ints just fine. but when I do:

var data = new formData(document.querySelector('form'));

let arr = [{
    Number: "12345678"
},
{
    Number: "87654321"
}
];

data.append('Phones', JSON.stringify(arr)); 
//OR
data.append('Phones', JSON.stringify(arr[0]));
data.append('Phones', JSON.stringify(arr[1]));
//OR
data.append('Phones[]', JSON.stringify(arr[0]));
data.append('Phones[]', JSON.stringify(arr[1]));
//OR
data.append('Phones[0]', JSON.stringify(arr[0]));
data.append('Phones[1]', JSON.stringify(arr[1]));

and then post to something like this:

[HttpPost]
public ActionResult SaveContact([FromForm]Contact contact)
{
    ...
}

The object is bound as its supposed to, with the correct values for Id, Name, But Phones contains nothing. Does anyone have some input here, its driving me nuts. Thanks!

2 Answers

Try to change your code to the following form:

let arr = ["123456","7895555"];

  formData.append('Phones[0].Number', arr[0]);
  formData.append('Phones[1].Number', arr[1]);

Result: enter image description here

Array type property with complex objects

const fd = new FormData();

const phones = [
  { number: '123', model: 'model x' },
  { number: '456', model: 'model y' },
];

for (var i = 0; i < phones.length; i++) {
  fd.append(`phones[][${i}][number]`, phones[i].number);
  fd.append(`phones[][${i}][model]`, phones[i].model);
}
Related