4

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);
}

2 Answers 2

6
// 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
  }
Sign up to request clarification or add additional context in comments.

Comments

0

Like Example

In order to allow ASP.NET Core model binder to bind an array you need to add array values multiple times with the same parameter name

For Eg :-

let formData: FormData = new FormData();
formData.append("name", "name");
for(let i = 0; i < Ids.length; i++) {
    formData.append("Ids", Ids[i]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.