igor fortaleza
igor fortaleza

Reputation: 31

Model being received empty in the controller after post

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.

Upvotes: 2

Views: 1594

Answers (2)

J&#243;zef Podlecki
J&#243;zef Podlecki

Reputation: 11283

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

Upvotes: 4

Jabberwocky
Jabberwocky

Reputation: 789

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

Upvotes: 1

Related Questions