由于可空字段为空,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/