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 both rendered with the help of HtmlHelper methods. The helper method for creting ddlOfficers is as follows:
@Html.DropDownListFor(x => x.OfficerID, Model.Officers, "<Choose>", new { id = "ddlAddressedOfficer" })
Where OfficerID is a Nullable<int>
For ddlApplicationTypes I had to write an extension method that would let me create dropdownlist for enum fields:
@Html.EnumDropDownListFor(x => x.ApplicationType, new { @class = "select-normal" })
Where ApplicationType is of type custom enum called AppType
public Enum AppType{
None=0,
Complaint,
Query,
Suggestion
}
I've decorated both OfficerID and ApplicationType properties with RequiredAttribute. When I don't select anything on ddlOfficers I get validation warning on submitting. But I don't get any warning when I don't select anything on ddlApplicationType. And I probably know the cause of the problem:If I compare the two select elements I can see that the first option (Choose) of ddlOfficers has no value specified, which when selected causes the validation to complain. But the first option of ddlApplicationType has value of "None". So the validation engine sees that the selected option has a value and simply ignores it. What would you suggest to do to get it working?
EDIT: To make things more clear to see here is the html for both select elements:
<select class="select-normal input-validation-error" data-val="true" data-val-required="Choose the addressed officer" id="ddlOfficers" name="OfficerID">
<option value=""><Choose></option>
<option value="1">Ben Martin</option>
<option value="2">Nick Carter</option>
<option value="3">Sebastian Van</option>
</select>
<select class="select-normal valid" data-val="true" data-val-required="Select the application type" id="ddlApplicationType" name="ApplicationType">
<option selected="selected" value="None"><Choose></option>
<option value="Complaint">Complaint</option>
<option value="Query">Query</option>
<option value="Suggestion">Suggestion</option>
</select>
<option value>-- select --</option>
. IfApplicationType
is a nullable enum with the[Required]
attribute, then it should be invalid if the first option is selected. – Meiosis