Search code examples
angularformsasp.net-coredata-bindingdeserialization

Binding form from Frontend (angular) to model in backend ASP.NET Core


I'm having problems binding array of objects to a list in my backend. Everything binds correctly beside that one array.

Here are photos of my problem notice that list of PrepTimes is null:

I tried all variations of:

    form.append(
      'prepTimes',
      JSON.stringify(this.recipeForm.value.recipePrepTime)
    );

    form.append(
      'prepTimes[]',
      JSON.stringify(this.recipeForm.value.recipePrepTime)
    );

    for (let prepTime of this.recipeForm.value.recipePrepTime) {
      form.append('prepTimes[]', JSON.stringify(prepTime));
    }

    this._recipeService.addRecipe(form);
  }

I tried removing and adding '[]', sending it without JSON.stringify() etc. I did all the variations I could do.

Console log for this.recipeForm.value.recipePrepTime:

this.recipeForm.value.recipePrepTime :>>  
(2) [{…}, {…}]
 0: {title: 'Prep Time', time: 1, unit: 'mins'}
 1: {title: 'Cook Time', time: 1, unit: 'hours'}
 length: 2
 [[Prototype]]: Array(0)

Solution

  • Post array of objects with FormData is different. You need to construct the FormData as:

    prepTimes[0].title="Prep Time" 
    prepTimes[0].time=1
    prepTimes[0].unit="mins"
    
    prepTimes[1].title="Cook Time" 
    prepTimes[1].time=1 
    prepTimes[1].unit="hours"
    
    let recipePrepTime: any = this.recipeForm.value.recipePrepTime;
    
    for (let i in recipePrepTime) {
        let prepTime = recipePrepTime[i];
    
        for (let k in prepTime) {
            form.append(`prepTimes[${i}].${k}`, prepTime[k]);
        }  
    }
    

    Demo @ TypeScript Playground