I have FormData object to which I set an array of integers.
document.querySelectorAll("input[name="genre"]:checked").forEach((e)=> genres.push(+e.value));
console.log(typeof(genres[0])); //number
if (genres.length > 0) {
formData.set("genreFilters", JSON.stringify(genres));
}
I am sending this FormData object by fetch()
to my ASP.NET API
fetch("/list", {
method: "POST",
body: formData
})
Whenever I check my request payload it appears to have selected values stored in the array
However, on the server side this array is always appear to be empty.
Here is my controller and request object on the server side.
public record GetAllBooksQuery : IRequest<GetAllBooksQueryResponse>
{
public int Page { get; set; }
public int CountPerPage { get; set; } = 30;
public int YearFrom { get; set; }
public int YearTo { get; set; }
public string Order { get; set; } = "Title";
public string Direction { get; set; } = "Ascending";
public int[] GenreFilters { get; set; } = Array.Empty<int>();
}
[Route("/list")]
public async Task<IActionResult> BookList(GetAllBooksQuery query)
{
var response = await _mediator.Send(query);
return Ok(_mapper.Map<GetAllBookResponse>(response));
}
Note: I tried to change content-type of my request to "application/json" but it didnt work.
2
Answers
The solution was simple. Because I'm not used to work with javascript I didn't know that when I use JSON.stringify() it actually returns string that I need to parse eventualy.
The issue here might be that you are using the FormData object to send your data, but your server-side code expects a JSON payload. When you send data using FormData, it is automatically encoded as multipart/form-data, which is a different format than JSON.
To fix this issue, you can try changing your server-side code to accept multipart/form-data format, or you can modify your client-side code to send the data as JSON.
If you want to send the data as JSON, you can update your client-side code to use JSON.stringify to convert the data to a JSON string before sending it:
Then, on the server-side, you should be able to deserialize the JSON payload using a JSON deserializer.
Note: You may also need to update the [Route("/list")] attribute on the server-side to [HttpPost("/list")].
If you want to accept multipart/form-data format in your server-side code, you can use the [FromForm] attribute to bind the form data to your model.
the [FromForm] attribute instructs ASP.NET to bind the form data to the GetAllBooksQuery model. This will work with the FormData object that you’re currently using in your client-side code.
Note: You should make sure that the name attribute of the file input element on the client-side matches the name of the property in your GetAllBooksQuery model.