How to make RequiredAttribute work with an enum field

后端 未结 2 1130
星月不相逢
星月不相逢 2021-01-19 09:58

I\'ve recently realized that RequiredAttribute does not work on enum fields. Let\'s say I have two select elements called ddlOfficers and ddlApplicationTypes on the form bot

相关标签:
2条回答
  • 2021-01-19 10:34

    There's nothing wrong with your custom helper. The HTML clearly shows that the required data validation has been added (data-val-required). Simply, the issue is that that your enum always has an acceptable value. You may not consider None acceptable, but from the enum's perspective, it's just fine. So you have two choices:

    1. Add your own custom validation to ensure that None is not selected. You'll need to handle this both client and server-side, because you're completely on your own here.

    2. If you can change the enum, you can remove the None option, and then simply use a nullable enum on your model/view model property, i.e.:

      public AppType? ApplicationType { get; set; }
      

      Then, the required validation will work as expected.

    0 讨论(0)
  • 2021-01-19 10:45
    [EnumDataType(typeof(AppType))]
    

    This class lets you map the underlying value in a column to a corresponding enumeration constant name. This lets you define an enumeration that contains descriptive values that correspond to database values, and then use the enumeration constant names instead of the database values when data is displayed.

    MSDN Article

    0 讨论(0)
提交回复
热议问题