ModelBinder invalid enum doesn't make IsValid = false;

302 Views Asked by At

Having the following Model that I pass from the view to the controller :

public class CheckoutIndexCommand {
    [Required]
    public DeliveryTimeType DeliveryTime { get; set; }
}

and this enum as DeliveryTimeType :

public enum DeliveryTimeType {
    MORNING = 1,
    AFTERNOON = 2
}

On the view:

@Html.DropDownListFor(m => m.DeliveryTime, Model.DeliveryTimeOptions)

On the Controller Submit Action I have ModelState.IsValid check.

This works perfect. I was just intrigued to know what happen if I submit the option with a non-valid value like :

<option name="NotValidEnumValue" selected>xxx</option>

the ModelState return true for ModelState.IsValid even the enum cannot match which is not desirable.

I was thinking on parsing the enum to check if it can be parsed and add the modelstate error manually and here is the question :

Is there any DataAnnotation or something that will check for valid Enum Value for me ?

already tried using this with no success :

[Required]
[EnumDataType(typeof(DeliveryTimeType))]
public DeliveryTimeType DeliveryTime { get; set; }
0

There are 0 best solutions below