Marc Rasmussen
Marc Rasmussen

Reputation: 20555

Model values are null

I have the following model:

[HttpPost("/case")]
public async Task<IActionResult> CreateCase([FromBody] Case model)
{
    if (!ModelState.IsValid)
        return BadRequest();

    _context.Cases.Add(model);
    await _context.SaveChangesAsync();

    return Success(model);
}

Here I post the following:

enter image description here

However, when it reaches the model has all the values set to null.

Can anyone tell me what I'm doing wrong?

Update

When i try to remove it so that my request looks like this:

enter image description here

Same thing happens

Case

    namespace API.Models
{
    public class Case
    {
        public long Id { get; set; }

        public string Name { get; set; }
        public string Description { get; set; }

        public int Size { get; set; }

        public long BuildingTypeId { get; set; }
        public BuildingType BuildingType { get; set; }

        public long BuildingPurposeId { get; set; }
        public BuildingPurpose BuildingPurpose { get; set; }

        public long ApplicationUserId { get; set; }
        public ApplicationUser ApplicationUser { get; set; }

        public long LocationId { get; set; }
        public Location Location { get; set; }

        public long FireStrategyId { get; set; }
        public FireStrategy FireStrategy { get; set; }

        public List<CaseMaterial> Materials { get; set; }

        public List<Installation> Installations { get; set; }

        public List<DocumentationFile> Files { get; set; }
    }
}

Upvotes: 0

Views: 85

Answers (3)

Alex Riabov
Alex Riabov

Reputation: 9175

The problem, as it's already mentioned in comments, is that you pass null for a non-nullable property, thus model binder fails. You should either update model to have nullable property

public class Case
{
    public long? Id { get; set; }

    // rest of properties
}

or don't specify it in body (in this case it will have default value - 0 for long)

Upvotes: 1

Burim Hajrizaj
Burim Hajrizaj

Reputation: 381

When you post your model is should look like this

{ ApplicationUserId: 1 ... }

what you are doing right now is that you are sending an object of Case inside anther JSON object.

Upvotes: 0

Shanaka Rusith
Shanaka Rusith

Reputation: 431

The class you require from the body is inside another object, so it cannot be mapped to the class. body should be { id: null ...} instead of { Case: { id: null ...} }

Upvotes: 1

Related Questions