Search code examples
asp.net-mvcrequiredfieldvalidatormodelstate

No required attribute added but ModelState is still false


I have a model with several properties of type enum. I populate all of them using new MVC Html helper method call EnumForDropDownList. Some of them are required, so I've added a RequiredAttribute. Somehow I always get ModelState=false for those ones which are not required. I discovered this with debugger: Here's the snapshot

When I take a look at the Messages.resx file I can see that "Cannot be empty" error is for RequiredAttribute:

  <data name="PropertyValueRequired" xml:space="preserve">
    <value>Cannot be empty</value>
  </data>

Know I don't understand

  1. Why is the ModelState false if the properties that fail validation are not required. (The only attribute is [Column] mapping).
  2. If somehow the RequiredAttribute gets added to those properties implicitly, then why don't I get client validation error like those with the Required Attribute?

P.S. If I select a value on those properties, then the problem goes away.

EDIT: Here's the model:

public class DocumentCitizen{
    [Column("DOCID")]
    public int? DocID { get; set; }
    [Column("SOCIALCAT")]
    public SocialCategory SocialCat { get; set; }
    [Column("GENDER")]
    public Gender Gender { get; set; }
    [Column("APPTYPE")]
    [Required(ErrorMessage="Please select the application type")]
    public ApplicationType {get;set; }
}

Solution

  • In fact @Gaurav is right and I should have known it from the beginning. If a property type is enum, then it means it can have a value in the range of enum values. (I somehow wasn't thinking about the property getting an invalid value, I just got stuck with validation thing). And why it was getting invalid value, in this case an empty string, is because I reconfigured the EnumDropdownListFor method to set the value of the first item to be an empty string. And then when it tried to assign that empty string to those properties with custom enum types, the ModelState obviously becomes invalid. The reason why I had reconfigured the EnumDropdownListFor is RequiredAttribute was not working as even if I didn't select anything, the first value was selected and therefore no vaidation error was raised.

    To overcome both problems, I just changed types of all my properties with enum type to their nullable version. This way both required attribute works and I can pass null to those with no Required Attribute.