ModelState错误:值"null"对于可为空的字段无效 [英] ModelState error: The value 'null' is not valid for nullable field
问题描述
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屋!