0
votes

I have a question regarding the validation in .net MVC 4.

I have a page with a ViewModel that has two properties

public Class SampleViewModel {
    public Gender Gender {get;set;}
    public Income Income {get;set;}
}

Both Gender and Income are Enum values.

Gender are required field in the dropdown and Income will only appear for Female customer. So income is only required when gender is Female in the application.

In the UI, the gender is display as dropdown option and the Income is display as radio button list.

I am trying to put RequiredIf attribute for the Income field and only check that when Gender is Female, however, since the Enum will have 0 in the default value, so it won't fail for the require field validation when the user does not select Income in the radio button list.

Something that I can think of is make use of the Range validation and apply the Range validation if the Gender is Female. Or If there is an option to force the radio button list to send back empty string if null of the option selected

Or is there a better approach or work around for that?

1

1 Answers

0
votes

Since enums cast to integers fairly easily, it's probably easier to use those as your model properties. Then, you can make the Income property nullable, which makes it work better with the RequiredIf attribute:

public class SampleViewModel {

    [Required]
    public int Gender {get;set;}

    [RequiredIf("Gender", (int)Gender.Female)]
    public int? Income {get;set;}
}

In your controller you then just have to cast them back to your enums:

(Gender)model.Gender

etc.