'How can i get list of custom model datas in formdata

I am unable to get the List of child details in the controller. This is a model in asp.net

   public class TestFileModel
{
    //public TestFileModel()
    //{
    //    ChildrensDetails = new List<ChildrensDetailsDataModel1>();
    //}
    public IFormFile? Photo { get; set; }
    public List<ChildrensDetailsDataModel1> ChildrensDetails { get; set; }
    public List<string> Ids { get; set; }
}
public class ChildrensDetailsDataModel1
{
    public string ChildCountry { get; set; } = null!;
}

This is the controller

 [HttpPost]
    [Route("UpdateUser")]
    public async Task<JsonResult> UpdateUser([FromForm] TestFileModel userDetailModel)
    {
        var userslist = await _userBusiness.UpdateUser(userDetailModel);
        return new JsonResult(new { userslist });
    }

This is the Angular save method code and service file

if (this.profileForm.invalid)
  return;
let formData: FormData = new FormData();
formData.append('Photo', this.selectedFile);
for (let index = 0; index <  this.profileForm.value.childrensDetails.length; index++) {
  formData.append('ChildrensDetails', this.profileForm.value.childrensDetails[index])
}
for(let i = 0; i < this.chartDataSetValue.length; i++) {
  formData.append("Ids", this.chartDataSetValue[i].toString());

}

 updateUser(userDetailModel:any):Observable<any> {
    return this.http.post<any>(`${UserProfileURLConstants.USER_PROFILE}`,userDetailModel);
}

But I am able to get Ids value unable to get ChlidrensDetails value. Image for details



Solution 1:[1]

Passing a set of objects via form-data is tricky that you can't straightly pass the object as:

ChildrensDetails[0]: { "ChildCountry": "Malaysia" }
ChildrensDetails[1]: { "ChildCountry": "Korea" }

Instead, you have to do as:

ChildrensDetails[0].ChildCountry: "Malaysia"
ChildrensDetails[1].ChildCountry: "Korea"

Assume this.profileForm.value.childrensDetails[index] returns value of:

{ "childCountry": /* Country name */ }

Modify the formData.append part for ChildrensDetails.

for (let index = 0; index < this.profileForm.value.childrensDetails.length; index++) {
  formData.append(`ChildrensDetails[${index}].ChildCountry`, 
    this.profileForm.value.childrensDetails[index].childCountry)
}

Test Scenario & Output

enter image description here

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yong Shun