ModelState.Isvalid not work for default value of boolean field

697 Views Asked by At

WEB API --->

public async Task<IHttpActionResult> CreatePost(ChildClient c)
{

if(!ModelState.IsValid)  {
throw ...
}
..

}
 public class Client
    {
        [Required]
        public bool HasBaseValue { get; set; } = true;
        [Required]
        public string Name { get; set; } = "stringvalue";
    }
    public class ChildClient : Client
    {
        [Required]
        public bool HasFieldValue { get; set; } = true;
        [Required]
        public string Name1 { get; set; } = "stringvalue";
    }

ModelState.Keys gives following errors: HasBaseValue,HasFieldValue if both fields are not supplied. why it still shows in error field even though default value is set. NOTE: default values are already populated in 'c object' when I debug and check by breakpoint.

1

There are 1 best solutions below

0
On

Achieve by skipping those fields from ModelState.IsValid to validate. As those default values fields are not posted so, ModelState.IsValid considering as invalid.(because, default value populate from API but ModelState.IsValid only validate posted value).