floormind
floormind

Reputation: 2028

Why is my post method not receiving the data that it is sent?

I have a post method, the parameter School is always null every time it is being called. I make sure to send the right data across, I am using Postman, but when I inspect it with a breakpoint, I get a null object.

What I send with Postman:

{
    "Id": "",
    "Name": "Test"
}

Controller:

[HttpPost]
public IActionResult Post([FromBody] School school)
{
    try
    {
        if (!ModelState.IsValid)
        {
            return BadRequest();
        }

        var schoolData = Mapper.Map<School, Data.School>(school);

        var schoolModel = _schoolRepository.AddSchool(schoolData);

        return CreatedAtRoute("GetSchool", new { id = schoolModel }, schoolModel);
    }
    catch (Exception e)
    {
        return LogException(e);
    }
}

Model:

public class School
{
    public Guid Id { get; set; }
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }
    public IEnumerable<Teacher> Teachers { get; set; }
    public IEnumerable<Class> Classes { get; set; }
}

Upvotes: 0

Views: 1326

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32072

The problem is that your model requires a Guid and you are sending an empty string:

"Id": ""

Regardless of the Id not being [Required], the model still cannot parse the data. What you can do, however, is to exclude it from binding:

public IActionResult Post([FromBody][Bind(Include = nameof(School.Name))] School school)

Or, a better option is to use a ViewModel. In this case, however, since you only have one property, I'd just use this:

public IActionResult Post([FromBody]string name)

Upvotes: 1

Related Questions