ModelState错误:值"null"对于可为空的字段无效 [英] ModelState error: The value 'null' is not valid for nullable field

查看:236
本文介绍了ModelState错误:值"null"对于可为空的字段无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ModelState引发错误,因为可为空的字段为空.

ModelState throws an error because nullable field is null.

我有一个模特:

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

}

控制器:

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.当我开始调试时,看到此错误

The 'errors' variable equals to 1. When I started debugging, I saw this error

为什么ModelState捕获错误? OrganizationId显然是nullable字段. 我看到了关于stackoverflow的主题,但由于在.net core中没有Global.asax,因此无法使用该解决方案.

Why did ModelState catch an error? OrganizationId is clearly a nullable field. I saw Topic on stackoverflow but couldn't use the solution because here is no Global.asax in .net core.

推荐答案

您的代码正在尝试在nullable int字段OrganizationID中插入字符串数据'null'.你自己为什么OrganizationID字段得到的是字符串'null'而不是null的值.这可能是parsing的原因.

Your code is trying to insert a string data 'null' in your nullable int field OrganizationID.As rest of your is not here, figure out by yourself why OrganizationID field is getting a string 'null' value instead of null. It may be a reason of parsing.

这篇关于ModelState错误:值"null"对于可为空的字段无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆