In my view model, i have a nullable DateTime property called BirthDate.

When i submit an invalid DateTime value to the controller, the ModelState.IsValid is false, saying that the BirthDate is an invalid DateTime.

How can i make ModelState to treat invalid nullable DateTime as a null value, instead of making it invalid?

有帮助吗?

解决方案

ModelState is bit bothersome with DateTime because everytime your posted input doesn't match Datetime formatting .isValid() is going to be false.

Have you considered using string to take in user input and later see if its possible to parse into DateTime.

Ps. this also occurs when trying to post and empty string: C# MVC 4 ViewModel not accepting null DateTime

Hope this helps :)

其他提示

you are doing the client side validation, then you dont worry about that validation if the birth date value is null or empty then you returns null.

public class DateFieldAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null || value == string.empty)
        {
            return null;
        }
        else
        {
   //Validate the Birth date.
        }
    }
}

If you return NULL then the Modelstate doesn't consider Birthdate field.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top