3

I want to send a list of integers inside an object to a POST API in C#. This is what I am doing:

const headers = new HttpHeaders().append(
  "Content-Disposition",
  "multipart/form-data"
);

let formData: FormData = new FormData();
formData.append("name", "name");
formData.append("Ids", JSON.stringify(Ids));
return this._http.post(
  `${environment.baseUrl}${this.companyApiUrl}`,
  formData,
  { headers: headers }
);

Where Ids is of type number[].

The following is the C# WebAPI:

public ActionResult<MyModel> Post([FromForm] MyModel model)
{
    ...
}

MyModel :

public class MyModel
{
    public string Name { get; set; }
    public List<int> Ids { get; set; } // I have also tried int[]
}

I am getting the following error from the Web API:

{"Ids":["The value '[5,6,7]' is not valid."]}

How do I achieve this? I want to keep the type of Ids in MyModel as List<int> or int[] (directly send the Ids without JSON parsing in the server).

3 Answers 3

7

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

let formData: FormData = new FormData();
formData.append("name", "name");
for(let i = 0; i < Ids.length; i++) {
    formData.append("Ids", Ids[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

If the field with a list of ids is not required the only way (that works for me) to handle empty value is not to append to formData at all. I also exclude 0, "", null and undefined inside Ids array by Number(id) > 0.

if (Array.isArray(Ids)) {
  Ids.forEach(
    (id: string) => Number(id) > 0 && formData.append('Ids', id),
  );
}

Comments

-1

.Net core post method

public ActionResult<MyModel> Post([FromBody]long[] ids)
{
.............
}

angular post method

post(ids:number[]): Observable<MyModel> {
let body = JSON.stringify(ids);
const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type':  'application/json'
    })
 };
 return this.httpclint.post<MyModel>(yourApiUrl, body, httpOptions)
    .pipe(
     catchError(this.handleError)
    );  
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.