Home > Software engineering >  ASP.NET Core: model invalid due to related ICollections
ASP.NET Core: model invalid due to related ICollections

Time:02-05

When submitting my post request, ModelState.IsValid is always false due to the related entities being empty.

    [Key]
    [Required()]
    public int ID {get; set;}

    [MaxLength(20)]
    [Required()]
    public string NAME {get; set;}

    public ICollection<ActorMovieJunction> NameJobJunction {get; set;}

Both the ID and the NAME show up as valid in the state model, but NameJobJunction being "null" creates an error.

I'm also using the [BindProperty] tag

CodePudding user response:

I think the problem is a new nullable feature net6. I highly recommend you to remove it or comment in project properties

 <!--<Nullable>enable</Nullable>-->

Or you will have to mark all nullable properties as nullable.

 public ICollection<ActorMovieJunction>? NameJobJunction {get; set;}

and IMHO never use [Bind] in the controller action parameters.

CodePudding user response:

You can try to give a default value to NameJobJunction:

public ICollection<ActorMovieJunction> NameJobJunction {get; set;}=new List<ActorMovieJunction>();
  •  Tags:  
  • Related