1

I'm trying to make a post request from my Angular frontend to the .net Core 3.1 backend, but in the controller method the argument object only gets by default 0 and null values;

let response = await fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(obj)
});
[ApiController]
[Route("[controller]")]
[ApiExplorerSettings(IgnoreApi = true)]
public class RequestController : ControllerBase
{
[HttpPost]
public async Task<IAResponseViewModel> PostAnswer([FromBody] IAResponseViewModel something)
{
   var temp = something.ToString();
         
   if (!ModelState.IsValid)
   {
      Console.WriteLine();
   }

   return something;
}
}
public class IAResponseViewModel
{
   public string AdministrationId { get; }
   public int RoundUsesItemId { get; }
    public int ResponseOptionId { get; }

}

The JSON object I see being submitted

{AdministrationId: "12345678-00e8-4edb-898b-03ee7ff517bf", RoundUsesItemId: 527, ResponseOptionId: 41}

When inspecting the controller method the 3 values of the IAResponseViewModel are null or 0 When I change the argument to object I get something with a value of

ValueKind = Object : "{"AdministrationId":"12345678-00e8-4edb-898b-03ee7ff517bf","RoundUsesItemId":523,"ResponseOptionId":35}"

I've tried with and without the [FromBody] attribute, changing the casing of the properties of the controller method's argument and the frontend argument, copy pasting the viewmodel attributes on to the submitted object keys, wrapping the posted object in a 'something' object. the ModelState.IsValid attribute shows as true. I've red other answers such as Asp.net core MVC post parameter always null & https://github.com/dotnet/aspnetcore/issues/2202 and others but couldn't find an answer that helped.

Why isn't the model binding working and how do I populate the viewmodel class I'm using with the json data?

1 Answers1

0

From a comment on my original question:

Could it be because the properties in IAResponseViewModel are 'get only'?

Indeed this was the problem. Giving the properties (default) set methods fixed the problem.