模型值为空

时间:2018-08-22 11:18:26

标签: c# http asp.net-core

我有以下模型:

[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);
}

我在这里发布以下内容:

enter image description here

但是,当到达model时,所有值都设置为null

有人可以告诉我我在做什么错吗?

更新

当我尝试将其删除以使我的请求看起来像这样时:

enter image description here

发生同样的事情

案例

    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; }
    }
}

3 个答案:

答案 0 :(得分:1)

您体内需要的类位于另一个对象内,因此无法将其映射到该类。正文应为{ id: null ...}而不是{ Case: { id: null ...} }

答案 1 :(得分:1)

问题已经在注释中提到,问题是您为不可空的属性传递了null,因此模型绑定程序失败。您应该更新模型以具有可为空的属性

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

    // rest of properties
}

或者不要在主体中指定它(在这种情况下,它将具有默认值-长为0)

答案 2 :(得分:0)

发布模型时,应该是这样

{   ApplicationUserId:1  ... }

您现在正在做的是在另一个JSON对象中发送Case对象。

相关问题