Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST list of object with Angular form-data to .Net Core Web API

I want to post a list of object to .Net core web API from angular 9 application, Here i am using form-data because i need to post image with data and this is working for me but now a list of object property added to my view model. Here is my code example:

// ViewModel
public class ViewModel
{
    public string Name { get; set; }
    public IFormFile Image { get; set; }
    public List<Connect> Connects { get; set; }
}

public class Connect
{
    public string Name { get; set; }
    public string Link { get; set; }
}
// .Net Core Action
[HttpPost]
public async Task<IActionResult> Post([FromForm] ViewModel vm)
{
}

// Angular component.ts
onSubmit() {
   const formData = new FormData();
   formData.append('name', this.model.name);
   formData.append('image', this.form.get('image').value);
   // Want add a list of object here to post with this
   formData.append('connects', this.model.connects);
}
like image 493
Khairul Alam Avatar asked Oct 15 '25 15:10

Khairul Alam


1 Answers

// Angular component.ts
  onSubmit() {
    const formData = new FormData();
    formData.append('name', this.model.name);
    for (let i = 0; i < this.model.connects.length; i++) {
      if (this.model.connects[i].name !== '' && this.model.connects[i].link !== '') {
        formData.append('connects[' + i + '][name]', this.model.connects[i].name);
        formData.append('connects[' + i + '][link]', this.model.connects[i].link);
      }
    }
    // Rest of the code
  }
like image 173
Khairul Alam Avatar answered Oct 17 '25 05:10

Khairul Alam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!