Post FromBody Always Null

55,038

Solution 1

You get always null because you need to encapsulate all your post variables inside only one object. Like this:

public class MyPostModel {
    public List<string> userSocs {get; set;}
    public int collegeId {get; set;}
}

and then

public async Task<IActionResult> GetStudentResults([FromBody] MyPostModel postModel)

Solution 2

If the model is null, check:

1) Where the data is sent: body, form? and based on that add the decorator to the action. For ex:

[HttpPost]
public JsonResult SaveX([FromBody]MyVM vm) { ... }

2) Check ModelState: if it's invalid the vm will not be bound so it will be null.

if (ModelState.IsValid) { ... }

Solution 3

Another reason for the model binding to fail (always null) is if the data type for a property doesn't match. For example here is a simple model:

public class MyService {
    public string JobId { get; set; }
    public int ServiceType {get; set;}
}

And here is some json that doesn't match:

{"JobId":1, "ServiceType":1}

I got caught with this when I was retrieving the JobId using jquery's .data function, it was automatically converting it to an int. Fixed it by using .attr function instead.

Solution 4

Also, make sure those variables inside your parameter class are declared as Public, (or they'll just keep returning as null)..

Solution 5

If you want to send two or more models, you should use this example:

[HttpPost]
public async Task<ActionResult> addUsuario([FromBody] Newtonsoft.Json.Linq.JObject datos)
{
    Usuarios user = datos["usuario"].ToObject<Usuarios>();
    Empresas empresa = datos["empresa"].ToObject<Empresas>();
    return Json(await _srv.addUsuario(user, empresa));
}
Share:
55,038
Alex Kibler
Author by

Alex Kibler

Updated on September 21, 2021

Comments

  • Alex Kibler
    Alex Kibler over 2 years

    I've got a new API that I'm building with ASP.NET Core, and I can't get any data POST'ed to an endpoint.

    Here's what the endpoint looks like:

    [HttpPost]
    [Route("StudentResults")]
    public async Task<IActionResult> GetStudentResults([FromBody]List<string> userSocs, [FromBody]int collegeId)
    {
        var college = await _collegeService.GetCollegeByID(collegeId);
        // var occupations = await _laborMarketService.GetOccupationProgramsBySocsAndCollege(userSocs, college);
        return Ok();
    }
    

    And here's what my payload that I'm sending through Postman looks like:

    {
        "userSocs": [
                "291123",
                "291171",
                "312021",
                "291071",
                "152031",
                "533011"
            ],
        "collegeId": 1
    }
    

    I'm making sure that I have postman set as a POST, with Content-Type application/json. What am I doing wrong?

  • Alex Kibler
    Alex Kibler about 7 years
    That wasn't an issue in .NET 4.5, was it? I could swear I remember sending multiple params in a POST
  • Tseng
    Tseng about 7 years
    @AlexKibler: Only if you send the parameters via form or get query. You can only have a single model in your body, so any non-basic type (int, string, etc.) will be serialized to the first model. In ASP.NET Core (indepentent of 4.5 or .NET Core) you can only have a single FromBody (in WebApi 2.x it was implicit), because WebAPI and MVC are now merged into a single framework, where they were distinct ones previously
  • Mo Zaatar
    Mo Zaatar over 5 years
    I spent many hours debugging why I'm getting null FormData, all was good but my request data was invalid. So my two cents, Please add if (!ModelState.IsValid) { ... } at the first line of your method to check that you have the right model first :) First things first
  • Francisco Goldenstein
    Francisco Goldenstein over 5 years
    Correct, that's what I described on the second point. In fact, you could create an action filter that checks Model.IsValid and if it's not valid return a validation message to the client. That way you don't have to do it every single action.
  • Warren Schwartz
    Warren Schwartz almost 5 years
    The ModelState.IsValid is a great troubleshooting suggestion!
  • Cata Hotea
    Cata Hotea about 4 years
    yup, this was my issue
  • Piotr Kula
    Piotr Kula almost 4 years
    Or create a Model that has those two models in them.. I'd rather stay away from JObect
  • MrApnea
    MrApnea almost 4 years
    Thanks! Missed that simple thing and this comment saved me a lot of time.
  • andHapp
    andHapp over 3 years
    You saved the day with this answer. I have an int field that is getting sent as a string by axios (e.g. "99" instead of 99). It's bizarre to me that the binding system doesn't create the object and bind the fields it can. Seems far easier to debug that way. You would also think it could do a conversion between certain data types.
  • Irshu
    Irshu almost 3 years
    my man, i've been scratching my head on this half day. turns out ModelState was Invalid. Thanks brother!