Frage

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?

War es hilfreich?

Lösung

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 :)

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top