Guga Todua
Guga Todua

Reputation: 522

ModelState error: The value 'null' is not valid for nullable field

ModelState throws an error because nullable field is null.

I have a model :

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

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

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.

Upvotes: 8

Views: 7146

Answers (2)

katrash
katrash

Reputation: 1165

You can clear all validation states at the beginning of the controller action by calling ModelState.Clear();. Then add any validation you need manually in the code.

Upvotes: 0

Shahjahan
Shahjahan

Reputation: 552

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.

Upvotes: 4

Related Questions