2

In my api Asp.Net Core 3.1, I have some controllers that receive viewModel, but when I post, the model arrives empty in the controller.

My ClientViewModel:

public class ClientViewModel
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public IEnumerable<OperationViewModel> Operations { get; set; }
}

My Add ClientController:

    [HttpPost]
    public async Task<ActionResult<ClientViewModel>> Add(ClientViewModel clientViewModel)
    {
    //...
    }     

Post Json:

  {
    "id": 0,
    "name": "Bradesco",
    "operations":[]
  }  

This happens to me on any controller that receives a model, put, post. I don't know what can be.

2 Answers2

4

You probably don't have ApiController attribute on controller so it tries to parse data in request as form data instead of JSON.

Either specify in client model [FromBody] attribute or add [ApiController] in controller which comes with other fancy functionalities.

source

Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50
1

You need to add the FromBody attribute in the controller method

[HttpPost("/my-endpoint")]
public async Task<ActionResult<ClientViewModel>> Add([FromBody] ClientViewModel clientViewModel)
{
  //...
}     

The from body attribute does exactly that. Takes the data and assuming you have the correct model (which you do) binds it to the model

Jabberwocky
  • 768
  • 7
  • 18