c# - 模型状态错误 : The value 'null' is not valid for nullable field

标签 c# asp.net-mvc asp.net-core

由于可空字段为空,ModelState 会引发错误。

我有一个模型:

public class PersonModel
{
    public int? ID { get; set; }

    [Required]
    [StringLength(256)]
    public string Title { get; set; }

    [Required]
    [StringLength(256)]
    public string Name { get; set; }

    [Required]
    [StringLength(256)]
    public string Lastname { get; set; }

    [StringLength(1024)]
    public string Description { get; set; }

    public int? OrganizationID { get; set; }

    public string Organization { get; set; }

}

Controller :
var errors = ModelState.Where (c => c.Value.Errors.Count > 0).Select (c => c.Value).ToList ();

if (!errors.Any ()) {
    Person entity;

    if (model.ID.HasValue && model.ID > 0) {
        if (!Session.HasClaim (DataCache.Claims.EditPerson))
            return BadRequest ();

        entity = Repository.GetPerson (model.ID.Value);
    } else {
        if (!Session.HasClaim (DataCache.Claims.AddPerson))
            return BadRequest ();

        entity = new Person ();
        Repository.AddPerson (entity);
        if (!model.OrganizationID.HasValue && !string.IsNullOrEmpty (model.Organization)) {
            var organization = new Organization () {
                Title = model.Organization
            };
            Repository.AddOrganization (organization);
            entity.Organization = organization;
        }
    }

    TypeMapper.MapPersonModelToEntity (model, entity);
    Repository.Save ();
}
'errors'变量等于1。当我开始调试时,我看到this error

为什么ModelState发现错误? OrganizationId显然是 nullable field 。
我看到了 Topic在 stackoverflow 上但无法使用该解决方案,因为这里没有 Global.asax.net core .

最佳答案

您的代码正在尝试插入字符串数据 'null'在您的 nullable int领域OrganizationID .因为你的其他人不在这里,你自己弄清楚为什么OrganizationID字段正在获取一个字符串 'null'值而不是 null .可能是parsing的原因.

关于c# - 模型状态错误 : The value 'null' is not valid for nullable field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56034324/

相关文章:

c# - 迁移到 ASP.NET Core RC2 后集成测试中断

c# - Visual Studio 2015 断 Razor Intellisense

c# - ASP.NET Core 中必需的查询字符串参数

c# - 保存循环或使用 2 种方法 - 约定与性能

c# - 波兰语符号规则添加 "in"和逻辑运算符

asp.net-mvc - 使用 jqGrid 删除 ASP.NET MVC 中的多条记录

c# - 如何在 Web Api Controller 中触发 OnActionExecuting?

c# - ASP.NET 5中Global.json中的项目部分的说明

c# - 使用 Entity Framework 的存储库模式检索复杂对象图的模式

c# - 需要帮助使用线程来监视指定文件夹中的 txt 文件